Skip to content

Commit f72e69c

Browse files
authored
Update Binary Gap.java
1 parent 20bc426 commit f72e69c

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

Easy/Binary Gap.java

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
class Solution {
2-
public int binaryGap(int N) {
3-
char[] binValues = Integer.toBinaryString(N).toCharArray();
4-
int oneIndex = -1;
5-
int maxDistance = 0;
6-
7-
for (int i=0; i<binValues.length; i++) {
8-
if (binValues[i] == '1') {
9-
if (oneIndex == -1) {
10-
oneIndex = i;
11-
}
12-
else {
13-
maxDistance = Math.max(i - oneIndex, maxDistance);
14-
oneIndex = i;
2+
public int binaryGap(int n) {
3+
int lastOnePosition = -1;
4+
int currPosition = 0;
5+
int maxGap = 0;
6+
while (n > 0) {
7+
int rem = n % 2;
8+
n /= 2;
9+
if (rem == 1) {
10+
if (lastOnePosition != -1) {
11+
maxGap = Math.max(maxGap, currPosition - lastOnePosition);
1512
}
13+
lastOnePosition = currPosition;
1614
}
15+
currPosition++;
1716
}
18-
19-
return maxDistance;
17+
return maxGap;
2018
}
2119
}

0 commit comments

Comments
 (0)