Leetcode 191. Number of 1 Bits
2016-01-22 04:32
351 查看
191. Number of 1 Bits
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
so the function should return 3.
Analysis:
This question is quite simple, you can just count the number of one bit using >>
or you can use n = n & (n - 1) to turn the last bit which is 1 to 0;
code:
public class Solution {
public int hammingWeight(int n) {
int result = 0;
for(int i = 0; i < 32; i++){
if((n & 1) == 1)
result++;
n = n >> 1;
}
return result;
}
}
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.
Analysis:
This question is quite simple, you can just count the number of one bit using >>
or you can use n = n & (n - 1) to turn the last bit which is 1 to 0;
code:
public class Solution {
public int hammingWeight(int n) {
int result = 0;
for(int i = 0; i < 32; i++){
if((n & 1) == 1)
result++;
n = n >> 1;
}
return result;
}
}
public class Solution { public int hammingWeight(int n) { int total_ones = 0; while(n != 0){ n = n & (n - 1); total_ones ++; } return total_ones; } }
相关文章推荐
- Leetcode 190. Reverse Bits
- 关系表示:被动与主动、连环关系合并
- 【快速高斯模糊的实现】
- Leetcode 260. Single Number III
- 解决Git问题之fatal: index-pack failed
- 安卓自定义view_GDI绘图 _2d绘图_canvas绘图
- Leetcode 137. Single Number II
- C语言实现工厂模式
- Passing Objects Between Android Activities
- 为arm 编译包含gd的php5
- [看看世界]书签备份
- ceshi
- OS X各版本原厂系统镜像校验值索引
- OS X各版本原厂系统镜像校验值索引
- 【推荐】iOS汉字转拼音第三方库
- 解决 LaTeX Error: Something's wrong--perhaps a missing \item.
- WebGL学习笔记(1)
- Hashcode Of A String In Java
- LeetCode 59. Spiral Matrix II
- iframe跨域通信方案