剑指 Offer 15. 二进制中1的个数
# 剑指 Offer 15. 二进制中1的个数 (opens new window)
# 1.与运算
分析:不管整数还是负数,先通过与运算取出低31位的数,这样不需要判断当前是负数还是整数。如果第一步n是负数则统计末尾1时,需要再加1。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
if(n==0) return 0;
int temp=n&0x7fffffff;
int add=n<0?1+(temp%2==1?1:0):(temp%2==1?1:0);
int a=temp>>1;
return add+hammingWeight(a);
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57