Exactly One Consecutive Set Bits Pair Problem
#3950
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3950.
You are given an integer n.
Return true if its binary representation contains exactly one adjacent pair of set bits, and false otherwise.
Example 1:
Input: n = 6
Output: true
Explanation:
- Binary representation of 6 is 110.
- There is exactly one adjacent pair of set bits ("11"). Thus, the answer is true.
Example 2:
Input: n = 5
Output: false
Explanation:
- Binary representation of 5 is 101.
- There is no adjacent pair of set bits. Thus, the answer is false.
Constraints:
0 <= n <= 10^5
Solution
Approach: Simulation
Walk through the bits of n from the lowest to the highest and remember the previous bit in pre. Whenever the current bit and pre are both 1, we have found an adjacent pair of set bits. If a pair was already seen (vis is true), there are at least two pairs and the answer is false; otherwise mark vis. At the end, the answer is vis.
Complexity: time O(log n), space O(1).
class Solution:
def consecutiveSetBits(self, n: int) -> bool:
pre = 0
vis = False
while n:
cur = n & 1
if pre == cur == 1:
if vis:
return False
vis = True
pre = cur
n = n >> 1
return vis