求二进制数中1的个数

给定一个整数,最快的速度计算1的个数



public class A_Bite {
public static void main(String[] args) {
// int[] n={0,1,0,0,0,1,1,1};
// count(n);
// count2(10);
// count3(100);
// count4(100);
count5(100);
}


static void count(int[] n) {
int count = 0;
for (int i = 0; i < n.length; i++) {
if (n[i] % 2 == 1) {
count++;
}
}
System.out.println("the number of 1 is :" + count);
}


static void count2(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n & flag) != 0) {
count++;
}
flag = flag << 1;
}
System.out.println("the number of 1 is :" + count);
}


/*
* 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减一,那么原来在整数最右边的1就会变为0,
* 原来在1后面的所有0就会变为1(如果最右边的1后面还有0的话)。其余的为不会影响到
* 例:一个二进制数11001100,从右边数起的第三位是1,把整个数减去1后,第三位变成了0,他后面的变成了1,前面的保持不变 得到11001011
* 减一得到的结果是把最右边第一个1开始的数都取反了,这时我们有原来的整数与减一之后的数做与运算,
* 从原来整数最右边一个1开始所有为都变为0.原整数有多少个1,就可以进行这个运算多少次。
*/
static void count3(int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n - 1);
}
System.out.println("the number of 1 is :" + count);
}


/**/
static void count4(int n) {
int count = 0;
while (n != 0) {
if ((n & 1) == 1) {
count++;
}
n = n >> 1;
}
System.out.println("the number of 1 is :" + count);
}


static void count5(int n) {
// Integer.bitCount(n);
System.out.println("the number of 1 is :" + Integer.bitCount(n));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值