两个数用二进制表示,有多少位不同

两个数异或,相同为0;不同为1。再调用方法判断有几个1。

代码段:

public class Hanshujiaohuan {
public static int sun(int a) {
int count=0;
while(a>0) {
if((a&1)==1)
count++;
a>>=1;
}
return count;
}

public static void main(String []args) {
System.out.println("输入一个数");
Scanner scan=new Scanner(System.in);
int a=scan.nextInt();
System.out.println("输入第二个数");
Scanner scanner=new Scanner (System.in);
int b=scanner.nextInt();
int c=(a^b);
Hanshujiaohuan s=new Hanshujiaohuan ();
int d=s.sun(c);
System.out.println("这两个数右"+d+"位不同");
}
}

猜你喜欢

转载自www.cnblogs.com/mianyang0902/p/10639537.html