二进制中1的个数

来源:互联网 发布:文明6秘籍控制台mac版 编辑:程序博客网 时间:2024/06/07 03:36

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

解题思路
思路1
定义0x01,左移进行与操作,判断1的个数。这里有一点需要注意的是,尽量通过0x01左移来实现,而不是0x8000等通过右移来实现,因为右移分为算数右移和逻辑右移,不小心写为了算数右移要出错。
思路2
n = n & (n - 1)操作是将n最右侧的1清0,可以实现统计1的个数。

public class erjinzhizhong1degeshu {    public int NumberOf1(int n) {        int count = 0;        while (n != 0) {            n = n & (n - 1);            count++;        }        return count;    }    public static void main(String[] args) {        System.out.println(new erjinzhizhong1degeshu().NumberOf1(-1));    }}