统计二进制中1的个数

第一种方法

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {  // 输入一个整数
        String str = Integer.toBinaryString(n);
        int num = 0;
        for(int i=0;i<str.length();i++){
            char c = str.charAt(i);
            if(c=='1'){
                num++;
            }
        }
        return num;
    }
}

第二种方法

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {  // 输入一个整数
        return Integer.bitCount(n);
    }
}
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务