191. Number of 1 Bits

一、题目

  1、审题

  

  2、分析

    统计给出的无符号整数的二进制形式中的含有的 1 的个数。

二、解答

  1、思路:

    方法一、

      采用 JAVA 的 toBinaryString 方法,求出其二进制形式的字符串形式,在统计含有的字符 ‘1‘  的个数。

    public int hammingWeight(int n) {
        String s = Integer.toBinaryString(n);
        int count = 0;
        for(char c: s.toCharArray())
            if(c == '1')
                count++;
        
        return count;
    }

  

  方法二、

    ①、通过 n & 1 求出 n 最后一位二进制的位数 end;采用变量 ones 统计 end 是 1 的个数;

    ②、n >>>= 1; n 在无符号右移一位;当 n == 0 时 跳出循环。

    public int hammingWeight2(int n) {
        int ones = 0;
        while(n != 0) {
            ones += n & 1;
            n = n >>> 1;
        }
        return ones;
    }

  方法三、

    n &= n -1;   每次从 n 删除一个二进制 1。

    public int hammingWeight(int n) {
        int res = 0;
        while(n != 0) {
            n &= n -1;    // 每次从 n 删除一个 1
            ++res;
        }
        return res;
    }

注意:

    Java 没有无符号类型, int 型表示范围为[ -2147483648,  2147483647];

    Java 中  int 类型是循环表示的,而  2147483648 其实就是   -2147483648,也即  Integer.MAX_VALUE+1==Integer.MIN_VALUE;

    

 

原文地址:https://www.cnblogs.com/skillking/p/9806859.html