二进制中1的个数 java实现

65 阅读1分钟

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

下面写出我的解法


public class weiyunxuan {
    //    编写一个函数,输入是一个无符号整数(以二进制串的形式),
//    返回其二进制表达式中数字位数为 '1' 的个数(也被称为 汉明重量).)
//    n - 1 & n 则 n中的二进制1少一个
    public int hammingWeight(int n) {
        int count = 0, temp = n;
        while (temp != 0) {
            temp = (temp - 1) & temp;
            // 5 101 4 100  => 4 100
            count++;
        }
        return count;
    }
    // 暴力解法
    public int hammingWeight01(int n) {
        //把int 转化为二进制的值 5 => 101
        String s = Integer.toBinaryString(n);
        System.out.println(s);
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1') {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        weiyunxuan weiyunxuan = new weiyunxuan();
        int i = weiyunxuan.hammingWeight01(5);
        System.out.println(i);

    }
}

参考链接 www.bilibili.com/video/BV1VU…

最后本人水平有限 文章难免出现错误 敬请指出 希望我们一同成长