Article directory
1. Title
Integer conversion. Write a function that determines how many bits need to be changed to convert integer A into integer B.
Example 1:
Input: A = 29 (or 0b11101), B = 15 (or 0b01111)
Output: 2
Example 2:
Input: A=1, B=2
Output: 2
hint:
- The range of A and B is between [-2147483648, 2147483647]
Click here to jump to the question .
2. Java problem solving
It’s too simple, just go to the code.
class Solution {
public int convertInteger(int A, int B) {
int ans = 0, AB = A ^ B;
while (AB != 0) {
if ((AB & 1) == 1) ans++;
AB >>>= 1;
}
return ans;
}
}
- Time: 0 ms, beats 100.00% of users using Java
- Memory: 37.04 MB, beats 75.23% of users using Java