# 868. Binary Gap

• Time: $O(\log n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 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