[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.

分析:

直接用"除二取余"的方法来获取二进制的值

代码如下:(C#)

public class Solution {
    public int HammingWeight(uint n) {
        int intResult = 0;
        uint intTemp = n;
        
        if(n<=1){
            return (int)n;
        }

        while(intTemp > 0){
            if(intTemp%2 ==1){
                intResult++;
            }
            intTemp = intTemp/2;
        }
        
        return intResult;
    }
}

同样的思路用Java提交会报错,主要原因如下:

    - 输入值n可能为负数(但应视其为无符号整数,但Java中实际上是没有无符号整数的)

所以采用:无符号右移操作,可以忽略符号位。

代码如下(Java):

public class Solution {
  public int hammingWeight(int n) {
        int ans = 0;
        while (n != 0) {
            ans += n & 1;
            n >>>= 1;
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/savageclc26/p/4803204.html