Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5 Output: true Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7 Output: false Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11 Output: false Explanation: The binary representation of 11 is: 1011.
Constraints:
1 <= n <= 231 - 1In this approach, we will use bitwise operations to compare each bit with its adjacent one. The key is to repeatedly XOR the number with itself shifted one position to the right, which will result in a number with all bits set to 1 if the original number has alternating bits. Such a number should satisfy (n & (n + 1)) == 0.
The function calculates the XOR of the number with itself shifted one bit to the right. If the number has alternating bits, the result will be all 1s in binary, satisfying the condition that XOR & (XOR + 1) equals zero.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1), Space Complexity: O(1)
This approach involves checking each bit pair iteratively. We will repeatedly check if the last two bits are the same or different by analyzing the least significant bits and shifting the number to the right iteratively.
This implementation analyzes the last two bits of the number by checking the modulus and right-shifting iteratively. It ensures they are different, ensuring the bits alternate.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log N), where N is the value of the number. Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Bitwise Comparison Approach | Time Complexity: O(1), Space Complexity: O(1) |
| Observation and Iterative Check | Time Complexity: O(log N), where N is the value of the number. Space Complexity: O(1) |
Counting Bits - Dynamic Programming - Leetcode 338 - Python • NeetCode • 159,557 views views
Watch 9 more video solutions →Practice Binary Number with Alternating Bits with our built-in code editor and test cases.
Practice on FleetCode