求二进制数中1的个数

来源:互联网 发布:淘宝网天猫购裱画材料 编辑:程序博客网 时间:2024/06/05 14:40

给定一个整数,最快的速度计算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));
}
}

0 0
原创粉丝点击