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;
    }
}

转载于:https://www.cnblogs.com/browselife/p/10645635.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值