1332. 判断一个整数中有多少个1

1332. Number of 1 Bits

Description

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

Have you met this question in a real interview?

Example

For example, the 32-bit integer 11 has binary representation 00000000000000000000000000001011, so the function should return 3.

描述
写一个函数,其以无符号整数为输入,而输出它所具有的“1”的位数(也被称为汉明权重)

您在真实的面试中是否遇到过这个题?  
样例
例如,32-bit整数“11”的二进制表示为“00000000000000000000000000001011”,因此该函数应返回3。
public class Solution {
    /**
     * @param n: an unsigned integer
     * @return: the number of ’1' bits
     */
    public int hammingWeight(int n) {
        // write your code here
        
        int res = 0;
        
        while(n > 1){
            //判断一个数的尾部是否为1
            res += n % 2;
            // 右移位
            n = n >> 1;
            
        }
        //统计的除了个位数之外的1的个数
        res = res + n;
        return res;
    }
}
public class Solution {
    /**
     * @param n: an unsigned integer
     * @return: the number of ’1' bits
     */
    public int hammingWeight(int n) {
        int cnt = 0;
        
        while (n > 0) {
            cnt += (n & 1);
            n >>= 1;
        }
        
        return cnt;
    }
}

猜你喜欢

转载自www.cnblogs.com/browselife/p/10645635.html
今日推荐