題目:
給定兩個整數(shù)A和B,
需要改變幾個二進(jìn)制位才能將A轉(zhuǎn)為B。
樣例輸入
10 8
樣例輸出
1
思路:
改變幾個即是,原兩個數(shù)之間有幾位是不同的,將兩個數(shù)異或運算,在同計解中1的個數(shù)即可。(統(tǒng)計1的個數(shù)在前邊詳細(xì)解釋過)
(Java代碼)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c= a^b;
int count = 0;
while(c!=0) {
c = c&(c-1);
count++;
}
System.out.println(count);
}
}