Q:
public class ai {
public static int foo(int x){
int countx = 0;
while(x != 0){
countx++;
x = x&(x-1);
System.out.println(x);
}
return countx;
}
public static void main(String []args){
System.out.println(foo(9999));
}
}
求输出是什么
A:
答案为8
&为逻辑与运算,将左右两边的数转为二进制并求与值,所以本题的运算过程如下:
x = 9999&9998 = 0010 0111 0000 1111 & 0010 0111 0000 1110 = 0010 0111 0000 1110 = 9998, countx = 1
x = 9998&9997 = 0010 0111 0000 1110 & 0010 0111 0000 1101 = 0010 0111 0000 1100 = 9996, countx = 2
x = 9996&9995 = 0010 0111 0000 1100 & 0010 0111 0000 1011 = 0010 0111 0000 1000 = 9992, countx = 3
x = 9992&9991 = 0010 0111 0000 1000 & 0010 0111 0000 0111 = 0010 0111 0000 0000 = 9984, countx = 4
x = 9984&9983 = 0010 0111 0000 0000 & 0010 0110 1111 1111 = 0010 0110 0000 0000 = 9728, countx = 5
x = 9728&9727 = 0010 0110 0000 0000 & 0010 0101 1111 1111 = 0010 0100 0000 0000 = 9216, countx = 6
x = 9216&9215 = 0010 0100 0000 0000 & 0010 0011 1111 1111 = 0010 0000 0000 0000 = 8192, countx = 7
x = 8192&8191 = 0010 0000 0000 0000 & 0001 1111 1111 1111 = 0000 0000 0000 0000 = 0 , countx = 8
所以程序最终输出为8.