问题描述
计算整数二进制形式中1
的个数。
举个例子:
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Update at 2020_0625
注意,n
可能是负数,所以while
循环中的条件不能是n > 0
,
而应该是n != 0
。
Update at 2020_0717
Thanks Y总
的lowBit()
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
while (n != 0){
n -= lowBit(n);
ans++;
}
return ans;
}
private int lowBit(int x){
return x & -x;
}
}
解法1
直接来看下实现:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
while (n != 0){
ans += (n & 1);
n >>>= 1;
}
return ans;
}
}
Enjoy it !
一位喜欢提问、尝试的程序员
(转载本站文章请注明作者和出处 姚屹晨-yaoyichen)