有两个int型(32位)的正整数,返回这两个数对应的二进制的数的位数不同的个数,即15 1111 8 1000 返回 3。
思路:每次比最后一位,然后向右移位即可,其中比最后一位有一个小技巧,就是数字和1做&运算,即得到最后一位。
代码:
public class Diff{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(Count(a,b));
}
private static int Count(int a,int b){
int count = 0;
int len = 32;
while(len--!=0){
//与运算
if(((a&1)^(b&1))==1){
count++;
}
//移位
a>>=1;
b>>=1;
}
return count;
}
}