bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 868. Binary Gap

868. Binary Gap

Leetcode Solutions

One Pass with Last Seen Index

  1. Initialize last to -1, which will hold the index of the last seen 1.
  2. Initialize maxDistance to 0, which will hold the maximum distance found.
  3. Iterate through each bit of n from right to left (least significant bit to most significant bit).
  4. For each bit, increment an index i starting from 0.
  5. If the current bit is 1, check if last is not -1 (which means this is not the first 1 found).
  6. If it's not the first 1, update maxDistance with the maximum of maxDistance and i - last.
  7. Update last to the current index i.
  8. After the loop, return maxDistance as the result.
UML Thumbnail

Store Indexes of's in Binary Representation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...