Binary Gap

EasyBit Manipulationbit manipulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a positive integer n, look at its binary representation. Two 1 bits are adjacent if only 0 bits (possibly none) lie between them. The distance between two bits is the difference of their positions; for example, the two 1s in "1001" are at distance 3. Return the longest distance between any two adjacent 1 bits. If n has fewer than two 1 bits, return 0.

Examples

Input: n = 22
Output: 2
22 is 10110. The adjacent pairs of 1s are at distances 2 and 1.
Input: n = 8
Output: 0
8 is 1000, which has a single 1 bit.
Input: n = 5
Output: 2
5 is 101; the two 1s are 2 apart.

Constraints

  • 1 <= n <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bit manipulation problems