Leetcode 191. Number of 1 Bits
来源:互联网 发布:小学古诗大全软件 编辑:程序博客网 时间:2024/05/21 04:43
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation00000000000000000000000000001011
, so the function should return 3.
解法一:O(1);
public class Solution{
public int hammingWeight(int n){
return Integer.bitCount(n);
}
}
解法二:O(k) k=1的个数
public class Solution{
public int hammingWeight(int n){
int num=0;
while(n!=0){
num+= n&1;
n>>>=1;//这里不能用>> 因为>>>移位以后不足的用0取代 而>>移位以后直接丢弃数据,不会补充
}
return num;
}
}
解法三:O(log2(n))
public class Solution{
public int hammingWeight(int n){
int count =0;
while(n>0) {
if(n%2 != 0)count ++;
n=n/2;
}
return count;
}
}
- 191. Number of 1 Bits Leetcode Python
- 【LeetCode】191.Number of 1 Bits
- [LeetCode]191.Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- [leetcode] 191. Number of 1 Bits
- <LeetCode OJ> 191. Number of 1 Bits
- Leetcode 191. Number of 1 Bits
- leetCode 191. Number of 1 Bits
- 191. Number of 1 Bits LeetCode
- Leetcode: 191. Number of 1 Bits(JAVA)
- LeetCode 191. Number of 1 Bits
- [LeetCode]191. Number of 1 Bits
- leetcode 191. Number of 1 Bits
- LeetCode *** 191. Number of 1 Bits
- [LeetCode]191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- leetcode-191. Number of 1 Bits
- Spring技术内幕之IOC容器的实现(01)-IOC容器初始化过程
- MD5 加密算法详细介绍
- JSON真的比XML好很多吗?
- openlayers入门之使用openlayers描述车辆运动轨迹
- LeetCode No.337. House Robber III
- Leetcode 191. Number of 1 Bits
- 一,http_python服务器
- 逗号表达式
- ABAP中使用for all entries in小结
- 单例模式的应用
- 很好的debug方式取代printf满天飞
- Java查找工程下继承了某父类的文件
- android 4.4 支持透明状态栏和透明导航栏
- SQL SERVER数据库 “可能发生了架构损坏。请运行DBCC CHECKCATALOG。“的错误修复