Number of 1 Bits
来源:互联网 发布:季后赛马刺vs雷霆数据 编辑:程序博客网 时间:2024/06/03 22:07
问题描述:
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.
解题思路:
计算数值n的32位2进制表示有多少位1,可以考虑设置变量k左移位判断,有则加1,
class Solution {
public:
int hammingWeight(uint32_t n) {
int sum=0;
for(unsigned long k=1;k<pow(2.0,32);k=k<<1)
{if((n&k)==k)
sum++;
}
return sum;
}
};
另外一种简洁方法如下:
public class Solution {
public int hammingWeight(int n) {
int re = 0;
while(0 != n)
{
n = n&(n - 1);//每比较一次n上最低位1被设置为0
++re;
}
return re;
}
}
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.
解题思路:
计算数值n的32位2进制表示有多少位1,可以考虑设置变量k左移位判断,有则加1,
class Solution {
public:
int hammingWeight(uint32_t n) {
int sum=0;
for(unsigned long k=1;k<pow(2.0,32);k=k<<1)
{if((n&k)==k)
sum++;
}
return sum;
}
};
另外一种简洁方法如下:
public class Solution {
public int hammingWeight(int n) {
int re = 0;
while(0 != n)
{
n = n&(n - 1);//每比较一次n上最低位1被设置为0
++re;
}
return re;
}
}
0 0
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- GObject对象系统
- oracle基础:插入
- 构造顺序表--合并两个按元素从小到大排列的顺序表
- 高质量C/C++编程指南(七)
- android Vibrator 振动开发
- Number of 1 Bits
- JavaWeb之Request && Response篇
- 深圳互联网为何能快速崛起?
- oracle基础:使用字符串
- Day One,配置ssh免密码登陆
- 面试总结-腾讯产品群面
- Aisan demand of film faced plywood will be climbing
- python + opencv 环境搭建
- android studio使用baidu map