二进制中1的个数
package test1;
public class test4 {
public static int num(int n) {
int count=0;
while (n!=0) {
if ((n & 1) !=0) {
count++;
}
n=n>>1;
}
return count;
}
public static void main(String[] args) {
System.out.println(num(9));
}
}
上面的思路是:
判断二进制数的最右边的数是不是1,接着右移之后再判断。缺点:负数。。。。
思路二:
把一个整数减去1,再和原来的整数做 与运算,会把这个整数的最右边的一个1变成0,那么整数中有多少个1就可以进行多少次这种操作。
package test1;
public class test4 {
public static int num(int n) {
int count=0;
while (n!=0) {
++count;
n=(n-1)& n;
}
return count;
}
public static void main(String[] args) {
System.out.println(num(9));
}
}

浙公网安备 33010602011771号