We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 20bc426 commit f72e69cCopy full SHA for f72e69c
Easy/Binary Gap.java
@@ -1,21 +1,19 @@
1
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
+ public int binaryGap(int n) {
+ int lastOnePosition = -1;
+ int currPosition = 0;
+ int maxGap = 0;
+ while (n > 0) {
+ int rem = n % 2;
+ n /= 2;
+ if (rem == 1) {
+ if (lastOnePosition != -1) {
+ maxGap = Math.max(maxGap, currPosition - lastOnePosition);
15
}
+ lastOnePosition = currPosition;
16
+ currPosition++;
17
18
19
- return maxDistance;
+ return maxGap;
20
21
0 commit comments