1522. Longest Alternating Bit Run
A signal technician records a reading as a positive integer n and inspects its binary form written without leading zeros. A stretch of that bit string is called flickering if every two neighbouring bits inside it differ, so 0101 flickers while 0110 does not. A single bit is always a flickering stretch of length 1.
Given n, return the length of the longest contiguous flickering stretch in its binary representation. For example, the binary form 1101011 has the longest flickering stretch 10101, of length 5. Scan the bits one at a time with shifts, keeping the current run length and the best seen so far. Aim for O(log n) time and O(1) extra space.
Example 1
- Input:
- n = 5
- Output:
- 3
- Explanation:
5 is 101 in binary, and all neighbouring bits differ, so the run is 3.
Example 2
- Input:
- n = 12
- Output:
- 2
- Explanation:
12 is 1100; the best flickering stretch is 10 (or 01) of length 2.
Constraints
1 ≤ n ≤ 231 - 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(log n)
- Space
- O(1)