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.

Source: leetcode | Difficulty: EASY
Tags: Bit manipulation

Starter code: class Solution:
    def hasAlternatingBits(self, n: int) -> bool:
        

Solutions:
class Solution:

	def hasAlternatingBits(self, n):
		if n % 2 == 0:
			n = n >> 1
		cnt = 0
		a = n
		while a > 0:
			cnt += 1
			a = a >> 1
		if cnt % 2 == 0:
			return False
		c = 1
		for i in range(1, cnt):
			c = c << 1
			if i % 2 == 0:
				c += 1
		return c == n


class Solution:

	def hasAlternatingBits(self, n):
		before = None
		while n != 0:
			d = n % 2
			if not before:
				before = d + 1
			else:
				if before == d + 1:
					return False
				before = d + 1
			n = n >> 1
		return True


class Solution:

	def hasAlternatingBits(self, n):
		res = []
		while n > 0:
			res.append(str(n % 2))
			n //= 2
		for i in range(1, len(res)):
			if res[i] == res[i - 1]:
				return False
		return True


class Solution:

	def hasAlternatingBits(self, n):
		prev = n % 2
		n = n // 2
		while n > 0:
			now = n % 2
			if now == prev:
				return False
			n = n // 2
			prev = now
		return True


class Solution:

	def hasAlternatingBits(self, n):
		return '00' not in bin(n) and '11' not in bin(n)


class Solution:

	def hasAlternatingBits(self, n):
		i = n % 2
		while n > 0:
			if i % 2 == 0:
				n /= 2
			else:
				n = (n - 1) / 2
			i += 1
		return n == 0


class Solution:

	def hasAlternatingBits(self, n):
		now = n & 1
		while n:
			print(n, n & 1)
			n >>= 1
			if n & 1 == now:
				return False
			else:
				now = n & 1
		return True


class Solution:

	def hasAlternatingBits(self, n):
		bin1 = str(bin(n)[2:])
		length = len(bin1)
		for i in range(0, length - 1):
			if bin1[i] == bin1[i + 1]:
				return False
		return True


class Solution:

	def hasAlternatingBits(self, n):
		bits = bin(n)
		return all((bits[i] != bits[i + 1] for i in range(len(bin(n)) - 1)))


class Solution:

	def hasAlternatingBits(self, n):
		prev = None
		while n:
			curr = n % 2
			if curr == prev:
				return False
			prev = curr
			n //= 2
		return True