Alternating Bit Checker
Given a positive integer n, determine whether its binary representation has alternating bits. That is, two adjacent bits must always have different values (for example, 1010 or 101).
Return true if n has alternating bits, and false otherwise.
[ "5" ]
Explanation. The binary representation of 5 is '101'. Adjacent bits alternate, so the result is true.
[ "7" ]
Explanation. The binary representation of 7 is '111'. Adjacent bits are identical, so the result is false.
[ "11" ]
Explanation. The binary representation of 11 is '1011'. The last two bits are equal ('11'), so the result is false.
[ "10" ]
Explanation. The binary representation of 10 is '1010'. Adjacent bits alternate, so the result is true.
[ "1" ]
Explanation. The binary representation of 1 is '1'. There are no adjacent bits to violate the rule, so the result is true.
[ "1431655765" ]
Explanation. The binary representation of 1431655765 consists of alternating '01' bits throughout 31 bits.
Follow-up: Could you perform the check in O(1) time complexity using bitwise arithmetic operations instead of a loop?
1 <= n <= 2^31 - 1
- Views
- 3