p191

LeetCode p191 Number of 1 Bits 题解

1.题目:

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

题意:

输入一个整数,返回它的二进制里面有多少个1.

2.解题思路:

见代码
注意 2147483648 没有符号位会变为 - 2147483648。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
while (n != 0) { // 2147483648 不能使用 n>0
if ((n & 1) == 1)
ans++;
n = n >>> 1;
}
return ans;
}
}


4.一些总结: