Binary Number with Alternating Bits

題目

  1. 先想到的是有沒有辦法透過 bitwise operation 來判斷,發現無法
  2. 看相鄰位置有沒有一樣的,最直覺就是用字串來判斷 => 可以利用 Python 的 built-in function bin 來把數字轉為 binary 字串

Python3 solution:

1
2
3
4
5
6
def hasAlternatingBits(self, n: int) -> bool:
b_str = bin(n)[2:] # 去掉前面的 '0b'
for i in range(len(b_str) - 1):
if b_str[i] == b_str[i + 1]:
return False
return True

評論

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×