剑指offer——二进制中1的个数

来源:互联网 发布:金属徽章定制价格淘宝 编辑:程序博客网 时间:2024/06/07 01:07

题目描述

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

思路
>>>移位运算符的使用
public class Solution {    public int NumberOf1(int n) {        int count = 0;        while(n != 0){            if((n&1) == 1)count++;            n = n>>>1;        }        return count;    }}

某次刷笔试题看到的方法,n不断与n-1进行&运算,直至n变为0
因为n减去1后,最低位的1以及后面的位都会取反

public class Solution {    public int NumberOf1(int n) {        int count = 0;        while(n != 0){            count++;            n = n&(n-1);        }        return count;    }}