二进制中1的个数

来源:互联网 发布:陈丹丹淘宝店 编辑:程序博客网 时间:2024/06/04 23:18

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


public class Solution {    public int NumberOf1(int n) {        int count =0;        int flag = 1;        while(flag!=0)        {            if((n & flag)!= 0)                count++;            flag = flag << 1;        }        return count;    }}
public class Solution {    public int NumberOf1(int n) {        int count = 0;        while(n != 0)        {            ++count;            n = (n-1) & n;        }        return count;    }}
0 0
原创粉丝点击