191. Number of 1 Bits
来源:互联网 发布:微信载入数据失败 编辑:程序博客网 时间:2024/06/06 01:42
1 题意
求一个32位的无符号整数在二进制下有多少个1
2 解题思路
两种办法,一种是迭代求出整数的二进制,但是如果无符号整数的值大于有符号的整数,那么将得到-1
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ans = 0; while (n != 0){ ans += n % 2; n /= 2; } return ans; }}
第二种方法是不停地清除n的二进制表示中最右边的1,这个适用所有的整数
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ans = 0; while (n!=0){ ans++; n &= (n-1); } return ans; }}
3 参考代码
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ans = 0; while (n!=0){ ans++; n &= (n-1); } return ans; }}
阅读全文
0 0
- 191.Number of 1 Bits
- 191.Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191.Number of 1 Bits
- Volatile关键字总结
- 《弃子长安》第十章 血染胡杨
- Maven学习总结系列二:Maven的安装和配置
- 洛谷P2633 Count on a tree
- Linux基础指令学习01
- 191. Number of 1 Bits
- 做市商业务是个啥
- Approaching (Almost) Any Machine Learning Problem | Abhishek Thakur—翻译
- Decorator
- 冒泡排序 选择排序 递归思想
- 移动端网页制作
- ArcMap欧氏距离工具提取图像骨架线
- C++——黑白棋(状态改变)
- RSA算法详解