题目描述:
Determine the number of bits required to flip if you want to convert integer n to integer m.
Notice
Both n and m are 32-bit integers.
Example
题目思路:
Given n = 31
(11111), m = 14
(01110), return 2
.
这题就是单纯的bit shift,然后每次shift都比较一下。注意的是对于负数,先要转换成它的2's complementary再做。
Mycode(AC = 16ms):
class Solution {
public:
/**
*@param a, b: Two integer
*return: An integer
*/
int bitSwapRequired(int a, int b) {
// write your code here
long la = (long)abs(a), lb = (long)abs(b);
if (a < 0) {
la = (long)4294967296 - abs(a);
}
if (b < 0) {
lb = (long)4294967296 - abs(b);
}
long diff = la ^ lb, bitCount = 0; // 10001
int times = 0;
while (diff > 0 && times < 32) {
bitCount += diff % 2;
diff >>= 1;
times++;
}
return (int)bitCount;
}
};