剑指offer15. 二进制中1的个数

题目

https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/

思路

方法一:使用Java转换成2进制
方法二:每次和1做与运算,然后右移一位

 public int hammingWeight(int n) {
        String string = Integer.toBinaryString( n);
        return string.length()-string.replaceAll("1", "").length();
    }

    public int hammingWeight2(int n) {
        int res = 0;
        while(n != 0) {
            //与运算  1&1=1  1&0=0
            res += n & 1;
            //右移一位
            n >>>= 1;
        }
        return res;
    }

后记:
小浩算法公众号有很多关于位运算的问题
可以总结一下

发布了33 篇原创文章 · 获赞 37 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/hagle_wang/article/details/105328146