-
Notifications
You must be signed in to change notification settings - Fork 153
/
BinaryGap.java
36 lines (29 loc) · 1.07 KB
/
BinaryGap.java
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
package BinaryGap;
class Solution {
public int solution(int N) {
// write your code in Java SE 8
int max_gap = 0;
int current_gap =0;
boolean counting = false;
// Using the "concept of bit manipulation" and "& operation"
while( N !=0 ){
if(counting == false){ // for the first "1"
if( (N&1) == 1){ // note: cannot use n&1 withoug "()"
counting = true; // start to count
}
}
else{ // counting = true
if( (N&1) ==0){ // note: cannot use n&1 withoug "()"
current_gap ++;
}
else{ // N & 1 == 1
max_gap = Math.max(max_gap, current_gap);
current_gap = 0; // reset
}
}
N = N >> 1; // shift by one (right side)
// note: cannot just write "N >> 1"
}
return max_gap;
}
}