-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryGap
46 lines (35 loc) · 997 Bytes
/
BinaryGap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/********************************************/
Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.
If there aren't two consecutive 1's, return 0.
Example 1:
Input: 22
Output: 2
Explanation:
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.
/******************************************/
class Solution {
public :
int binaryGap(int N) {
String temp="";
while(N!=0) {
temp=N%2+temp;
N=N/2;
}
int[] A = new int[32];
int j=0;
for(int i=0;i<temp.length();i++) {
if(temp.charAt(i)=='1') {
A[j]=i;
j++;
}
}
int ans = 0;
for (int i = 0; i < temp.length() - 1; ++i)
ans = Math.max(ans, A[i+1] - A[i]);
return ans;
}
}