n & n-1 会把数字中最后等于1 的数字抹掉
1100 & 1011 == 1000 把第二位上的1 给去掉了
1011 & 1010 == 1010 最后一位的0抹掉了
利用这点我们可以做题了
1 是否是2的幂
思路:就是在2进制中 1的个数为1就好了 1, 10, 100,前面全补零到32位
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0:
return False
return (n&n-1) == 0
2 是否是4的幂
思路:在2的幂基础上再通过位运算筛选一下
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
#二进制思想 2的幂 1 10 100 1000 这些可以 是n&n-1 == 0
#观察一下 需要过滤掉 10 1000 10000 这些数& 0101 等于0
return (num&num-1) == 0 and (num & 0x55555555) !=0
3 位1 的个数 191
思路:有多少个1就能执行多少次
C++
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
while(n>0){
n = n & (n-1);
ret ++;
}
return ret;
}
};
顺便写下3的幂
4 326
这个比较通用,思路是 找到整数范围内最大的3的幂,然后 这个数如果整出给到的n 就说明n是3的幂
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
import math
max_value = 0x7fffffff;
k = int(math.log(max_value) / math.log(3));
return 3 ** k % n == 0