当前位置: 首页 > 工具软件 > Flip! > 使用案例 >

lintcode: Flip Bits

袁琪
2023-12-01

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);
    }
};
 类似资料:

相关阅读

相关文章

相关问答