LintCode Flip Bits

Determine the number of bits required to flip if you want to convert integer n to integer m.
Have you met this question in a real interview? Yes
Example
Given n = 31 (11111), m = 14 (01110), return 2.
Note
Both n and m are 32-bit integers.

class Solution {
public:
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    int bitSwapRequired(int a, int b) {
        // write your code here
        int diff = a ^ b;
        int count = 0;
        while (diff) {
            count++;
            diff = diff & (diff - 1);
        }
        return count;
    }
};

posted @ 2015-09-13 22:46  卖程序的小歪  阅读(394)  评论(0编辑  收藏  举报