lintcode: Flip Bits

来源:互联网 发布:mac 修改文件夹的权限 编辑:程序博客网 时间:2024/05/29 14:12

Determine the number of bits required to flip if you want to convert
integer n to integer m.

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 num_of_1(int a){        int num = 0;        while (a){            if (a >> 1){                num++;            }            a = a >> 1;        }        return num;    }    */    //上面程序当a为负数时错误    int num_of_1(int a){        int num=0;        for(int i=0;i<32;i++){            if(a&(1<<i)){                num++;            }        }        return num;    }    int bitSwapRequired(int a, int b) {        // write your code here        int XOR=a^b;        return num_of_1(XOR);    }};
1 0
原创粉丝点击