Leetcode 693 - Binary Number with Alternating Bits

Problem Statement

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.

Solution

1
2
3
4
5
6
7
8
9
class Solution(object):
def hasAlternatingBits(self, n):
b = bin(n)[2:]
for i, c in enumerate(b[:-1]):
if b[i] == b[i + 1]:
return False
return True

Time: O(N) where N is the number of bits in a number.

Space: O(N) to store the binary string of n.

Explanation

The first step is to convert the string into its binary string representation and the finally loop through it and making sure that the next bit is not the same as the current bit.