LeetCode Solutions
868. Binary Gap
Time: $O(\log n)$ Space: $O(1)$
class Solution {
public:
int binaryGap(int n) {
int ans = 0;
// D := distance between any two 1's
// Initialized to a reasonable small value
for (int d = -32; n; n /= 2, ++d)
if (n & 1) {
ans = max(ans, d);
d = 0;
}
return ans;
}
};
class Solution {
public int binaryGap(int n) {
int ans = 0;
// D := distance between any two 1's
// Initialized to a reasonable small value
for (int d = -32; n > 0; n /= 2, ++d)
if ((n & 1) == 1) {
ans = Math.max(ans, d);
d = 0;
}
return ans;
}
}
class Solution:
def binaryGap(self, n: int) -> int:
ans = 0
d = -32 # Distance between any two 1's, initialized to a reasonable small value
while n:
if n & 1:
ans = max(ans, d)
d = 0
n //= 2
d += 1
return ans