题解 | #二进制中1的个数#

二进制中1的个数

http://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8

经典的位运算
获得一个数它二进制中1的个数就是用它的每一个二进制位和1做相与
(这时被比较的那个工具数除了1,其他位的都是0,因此要左移工具数,左移补0比较好)
如果不为0说明这一位就是1,如果为0就说明为0。

public class Solution {
    public int NumberOf1(int n) {
        int tool = 1;//设置工具比较器,用来和n的每一位相与
        int count = 0;//设置计数器
        while(tool != 0){
            if((n & tool) != 0)count++;//这种与或非的位运算要加上小括号
            tool = tool << 1;
        }
        return count;
    }
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务