x & 1 == 1 OR == 0 判断奇偶(x % 2 == 1)
x = x (x-1) => 清零最低位的1
x & -x => 得到最低位的1
异或
x ^ 0 = x
x ^ x = 0
a ^ b = c => a ^ c = b ,b ^ c = a
leetcode
191.位为1的个数
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while (n != 0):
count += 1
n = n & (n - 1)
return count
if __name__ == "__main__":
s = Solution()
num = 0b11100001
print(s.hammingWeight(num))
231. power of two
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return (n != 0) & (n & (n - 1) == 0)
if __name__ == "__main__":
s = Solution()
num = 16
print(s.isPowerOfTwo(num))
338. counting bits