3950. Exactly One Consecutive Set Bits Pair
Description
You are given an integer n.
Return true if its binary representation contains exactly one pair of consecutive set bits, and false otherwise.
Β
Example 1:
Input: nums = 6
Output: true
Explanation:
- Binary representation of 6 is
110. - There is exactly one pair of consecutive set bits (
"11"). Thus, the answer istrueβββββββ.
Example 2:
Input: nums = 5
Output: false
Explanation:
- Binary representation of 5 is
101. - There are no consecutive set bits. Thus, the answer is
falseβββββββ.
Β
Constraints:
0 <= n <= 105
Solutions
Solution 1: Simulation
We use a variable \(\textit{pre}\) to record the digit of the previous bit, initialized to \(\textit{pre} = 0\), and another variable \(\textit{vis}\) to record whether a pair of consecutive set bits has already been found, initialized to \(\textit{vis} = \text{false}\).
Iterate through each binary bit of \(n\), and denote the current binary bit as \(\textit{cur}\). If \(\textit{pre} = \textit{cur} = 1\), and if \(\textit{vis} = \text{true}\) at this moment, it indicates that there are multiple pairs of consecutive set bits, so we directly return \(\text{false}\). Otherwise, we set \(\textit{vis}\) to \(\text{true}\). Then, we update \(\textit{pre} = \textit{cur}\) and continue to iterate through the next binary bit.
After the iteration ends, if \(\textit{vis} = \text{true}\), return \(\text{true}\); otherwise, return \(\text{false}\).
The time complexity is \(O(\log n)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |