剑指 Offer 15. 二进制中1的个数

public int hammingWeight(int n) {
        //先将n转成二进制数?
        String num = Integer.toBinaryString(n);
        int count = 0;
        char[] c = num.toCharArray();
        for (char value : c) {
            if (value == '1') {
                count++;
            }
        }
        return count;
    }

 

 


位运算:

public int hammingWeight(int n) {
        int count = 0;
        int flag = 1;
        while (flag>0){
            if((n&flag)>0){
                count++;
            }
            flag = flag<<1;
        }
        return n>=0?count:count+1;
    }

 

 


public int hammingWeight(int n) {
        int count = 0;
        while (n!=0){
            count++;
            n = (n-1)&n;
        }
        return count;
    }

 

 将一个数减去1,再与它自身做与运算,得到的结果就是把最右边的1变成了0;

 

posted @ 2020-08-08 18:00  欣姐姐  阅读(97)  评论(0编辑  收藏  举报