剑指Office-二进制中1的个数

//请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 
//2。 
//
// 示例 1: 
//
// 输入:00000000000000000000000000001011
//输出:3
//解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
// 
//
// 示例 2: 
//
// 输入:00000000000000000000000010000000
//输出:1
//解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
// 
//
// 示例 3: 
//
// 输入:11111111111111111111111111111101
//输出:31
//解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 
//
// 
//
// 注意:本题与主站 191 题相同:https://leetcode-cn.com/problems/number-of-1-bits/ 
// Related Topics 位运算


//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        
    }
}
//leetcode submit region end(Prohibit modification and deletion)

提交

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
          return Integer.bitCount(n);
    }
}

在这里插入图片描述

内部实现

public static int bitCount(int i) {
  // HD, Figure 5-2
   i = i - ((i >>> 1) & 0x55555555);
   i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
   i = (i + (i >>> 4)) & 0x0f0f0f0f;
   i = i + (i >>> 8);
   i = i + (i >>> 16);
   return i & 0x3f;
}

解法2

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        // return Integer.bitCount(n);
        int count = 0;

        while(n!=0){
            n &= (n-1);
            count++;
        }

        return count;

    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TrueDei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值