191. Number of 1 Bits
原题链接:https://leetcode.com/problems/number-of-1-bits/description/
实现如下:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.hammingWeight(2147483647));
System.out.println(s.hammingWeight(2));
System.out.println(s.hammingWeight(3));
System.out.println(s.hammingWeight(11));
}
// 官方答案二:利用了一些规律性手段来提高效率
public int hammingWeight(int n) {
int sum = 0;
while (n != 0) {
sum++;
n &= (n - 1);
}
return sum;
}
// 官方答案一
public int hammingWeight2(int n) {
int bits = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) {
bits++;
}
mask <<= 1;
}
return bits;
}
// you need to treat n as an unsigned value
public int hammingWeight1(int n) {
// 哈哈,接受了上一题的洗礼,这一题就很简单啦!你要问上一题是什么?请看下面参考内容吧!
// 奶奶的,以为这个答案是必过的,谁知官方系统不按常理出牌,测试用例里面竟然有:2147483648(没错,就是比 Integer.MAX_VALUE 还要大一)
// 没办法了,参考官方答案吧!
int res = 0;
for (int i = 0; i < 32 && n > 0; i++) {
if ((n & 1) == 1) {
res++;
}
n >>>= 1;
}
return res;
}
}