[
math
bit manipulation
]
Leetcode 0868 Binary Gap
Problem statement
https://leetcode.com/problems/binary-gap/
Solution
Keep index of last found 1
. Iterate through lesser to larger bits and if we meet non-zero bit, update answer and index of last seen bit.
Complexity
Time and space complexity is O(32)
Code
class Solution:
def binaryGap(self, n):
last, ans = -1, 0
for i in range(32):
if n & (1<<i):
if last != -1: ans = max(ans, i - last)
last = i
return ans