您的位置:首页 > 其它

[leetcode]Number of 1 Bits

2015-12-09 22:13 344 查看
题目描述如下:

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,自然想到一位一位向右位移,数出1的个数(这里要注意,加入用的是Java,Java中的int是有符号的,也就是说32bit里还包含负数,输入2147483648时超出输入参数的范围)。

在网上看到另一种算法,拉过来学习一下:

假设n= 1111000111000 那 n-1 = 1111000110111, (n-1) & n = 1111000110000,刚好把最后一个1给干掉了。也就是说, (n-1)&n 刚好会从最后一位开始,每次会干掉一个1.这样速度就比下面的快了。有几个1,执行几次。

代码如下:

public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n - 1);
count ++;
}
return count;
}
}


题目链接:https://leetcode.com/problems/number-of-1-bits/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: