您的位置:首页 > 其它

[LeetCode][数论]Number of 1 Bits

2016-03-24 15:44 579 查看
题目描述:

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,必然涉及到位运算

过程:关于位运算的题目相对不是很熟练,可能是对于二进制表示或者相关的数学知识理解的还不够深入,但慢慢补充自己的数学内涵,这道题目有一个很关键的规则需要理解:就是n&n-1会使原n中1的个数-1,基于这个信息我们可以判断从n到0需要几次n&n-1,这是一个问题的转换过程,不必硬性计算32位的内容

代码实现:

public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ret = 0;

while(0 != n){
n = n&(n-1);
++ret;
}

return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: