首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode#191. Number of 1 Bits(位1的个数)

Leetcode#191. Number of 1 Bits(位1的个数)

作者头像
武培轩
发布2018-09-28 15:13:06
4220
发布2018-09-28 15:13:06
举报
文章被收录于专栏:武培轩的专栏武培轩的专栏

题目描述

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例 :

输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011

示例 2:

输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000

思路

思路一:

用Integer.bitCount函数统计参数n转成2进制后有多少个1

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

思路二:

如果一个整数不为0,那么这个整数至少有一位是1。

如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。

其余所有位将不会受到影响。

思路三:

用flag来与n的每位做位于运算,来判断1的个数

代码实现

package BitManipulation;

/**
 * 191. Number of 1 Bits(位1的个数)
 * 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
 */
public class Solution191 {
    public static void main(String[] args) {
        Solution191 solution191 = new Solution191();
        int n = 11;
        System.out.println(solution191.hammingWeight(n));
    }

    /**
     * 用Integer.bitCount函数统计参数n转成2进制后有多少个1
     *
     * @param n
     * @return
     */
    public int hammingWeight(int n) {
        return Integer.bitCount(n);
    }

    /**
     * 如果一个整数不为0,那么这个整数至少有一位是1。
     * 如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。
     * 其余所有位将不会受到影响。
     *
     * @param n
     * @return
     */
    public int hammingWeight_2(int n) {
        int count = 0;
        while (n != 0) {
            count++;
            n = (n - 1) & n;
        }
        return count;
    }

    /**
     * 用flag来与n的每位做位于运算,来判断1的个数
     *
     * @param n
     * @return
     */
    public int hammingWeight_3(int n) {
        int count = 0;
        int flag = 1;
        while (flag != 0) {
            if ((flag & n) != 0) {
                count++;
            }
            flag = flag << 1;
        }
        return count;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-09-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路
  • 代码实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档