首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指Office-二进制中1的个数

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

作者头像
手撕代码八百里
发布2020-07-28 09:19:29
2660
发布2020-07-28 09:19:29
举报
文章被收录于专栏:猿计划猿计划
//请实现一个函数,输入一个整数,输出该数二进制表示中 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;

    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-03-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 提交
  • 内部实现
  • 解法2
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档