LeetCode[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 00000000000000000000000000001011, so the function should return 3.

分析:

题目要求算出一个int数二进制表示中1的个数。

n和n-1按位与可以去掉n二进制表示中最右边一位1.

令 n =1101011000

则 n-1=1101010111

n&(n-1)=1101010000

经过K次n&n-1,n变为0.K即n的二进制表示中1的个数。

代码:

public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n &= n - 1;
count++;
}
return count;
}
}

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :