describe
Integer conversion. Write a function that determines how many bits need to be changed to convert integer A to integer B. The range of A and B is between [-2147483648, 2147483647].
Example 1:
Input: A = 29 (or 0b11101), B = 15 (or 0b01111) Output: 2
Example 2:
Input: A = 1, B = 2
Output: 2
Analysis: Determining how many bits need to be changed to convert integer A to integer B means that A needs to change how many binary bits to convert to B, that is, there are several binary bits in A that are different from B, and bit operations and shifts are required operation .
C language
int convertInteger(int A, int B){
int a=A^B;//bitwise XOR
int count=0;
while(a){
if((a & 1) != 0){
count++;//calculate the number of 1
}
a>>= 1;//Compared from the rightmost binary bit of a, the number of bits is shifted to the right one by one, and the leftmost sign bit is complemented
}
return count;
}
int main(){
int a,b;
scanf("%d%d",&a,&b);
int count=convertInteger(a,b);
printf("%d",count);
}
Java
import java.util.Scanner; public class Solution { public static int convertInteger(int A, int B) { int a=A^B;//bitwise XOR int count=0; int i; for(i=31;i>=0;i--) { if(((a>>>i)&1)==1)//Shift i bits to the right, add 0 to the left count++;//calculate the number of 1 } return count; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a= sc.nextInt(); int b= sc.nextInt(); int count=convertInteger(a,b); System.out.println(count); sc.close(); } }