Skip to content

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
class Solution {
 public:
  int binaryGap(int n) {
    int ans = 0;

    // d := the distance between any two 1s
    for (int d = -32; n; n /= 2, ++d)
      if (n % 2 == 1) {
        ans = max(ans, d);
        d = 0;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int binaryGap(int n) {
    int ans = 0;

    // d := the distance between any two 1s
    for (int d = -32; n > 0; n /= 2, ++d)
      if (n % 2 == 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  # the distance between any two 1s

    while n:
      if n % 2 == 1:
        ans = max(ans, d)
        d = 0
      n //= 2
      d += 1

    return ans