15.二进制中1的个数
剑指offer原题主要意思:统计某数字的二进制表示中1的个数。需要考虑正负数。
LeetCode题目:https://leetcode.cn/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/description/
考察点:优先使用移位代替除法、负数补码。
思路一:二进制转换
此方法仅适用于 LeetCode 的原题,因为没有考虑负数的情况(如果 n 是负数,负数是补码的形式存在,每次右移会在最高位补 1,会陷入死循环。)
进行二进制的转换,每次加上余数即可。
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>= 1;
}
return res;
}
}
(推荐)思路二:n & (n - 1)
n & (n - 1) 可以去除 n 的二进制中最后一个 1。适用于正负数。
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}