美文网首页
【剑指15】二进制中1的个数

【剑指15】二进制中1的个数

作者: 浅浅星空 | 来源:发表于2019-06-11 23:47 被阅读0次

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

分析

1.位运算

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

2.Integer自带的方法

public int NumberOf1(int n) {

    return Integer.bitCount(n);

}

相关文章

网友评论

      本文标题:【剑指15】二进制中1的个数

      本文链接:https://www.haomeiwen.com/subject/kyshfctx.html