一、191. 位1的个数
1.1、题目描述
class Solution(object):
def hammingWeight(self, n):
count = 32
c = 0
while count > 0:
if n&1 == 1:
c += 1
n >>= 1
count -= 1
return c
1.2.2、位操作
1.3、401. 二进制手表
1.4、693. 交替位二进制数
1.5、762. 二进制表示中质数个计算置位
二、190. 颠倒二进制位
2.1、题目描述
class Solution:
def reverseBits(self, n):
res = 0
count = 32
while count:
res = 1 # n右移,为下个循环提供最低位
count -= 1
return res
三、231. 2的幂
3.1、题目描述
3.2.1、位运算
class Solution(object):
def isPowerOfTwo(self, n):
return n > 0 and (n&(n-1) == 0)
3.3、326. 3的幂
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n bool:
# 首先是2的次幂
if num int:
# 异或
ans = 0
while x != 0 or y != 0:
if (x&1) != (y&1):
ans += 1
x >>= 1
y >>= 1
return ans