Convert Integer A to Integer B
Determine the number of bits required to convert integer A to integer B
Example
Given n = 31, m = 14,return 2
(31)10=(11111)2
(14)10=(01110)2
--------------- codes ---------------------------
class Solution {
public:
/**
*@param a, b: Two integer
*return: An integer
*/
int bitSwapRequired(int a, int b) {
// write your code here
//bug here: remember to consider sing of a and b
unsigned int a_or_b = (unsigned int)a^(unsigned int)b;
int cnt = 0;
while (a_or_b) {
cnt += a_or_b&1;
a_or_b = a_or_b >> 1;
}
return cnt;
}
};
No comments:
Post a Comment