Flip Bits

来源:互联网 发布:网络直播都有什么内容 编辑:程序博客网 时间:2024/06/11 08:20

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.

看到题目的第一想法是异或操作,c = a ^ b,然后右移求c的1的个数即为a,b不同的二进制位数,但是一提交不对,为什么呢?思路是对的,只是细节没有考虑清楚,假如a,b异号,那么c必然是小于0的数,然而对于一个小于0 的数执行右移操作会进入死循环,因为带符号的数右移会在右边补充符号位,而不是0。既然这样的话,-1右移会进入死循环;那怎么解决呢?貌似要分情况了,当a,b同号时,直接右移统计1的个数是没有问题的;当a,b异号时,则要求出c的源码,然后统计源码减1中0的个数,这次不是统计1,而是统计0了。另外还有一个细节需要记住,因为在补码的时候,是在原码的基础上取反,然后加了一个1,那为了跟补码的情况保持一致,必须讲原码减去一个1,这样0的个数才是原补码1的个数,这个细节非常重要。

class Solution {public:    /**     *@param a, b: Two integer     *return: An integer     */    int bitSwapRequired(int a, int b) {    // write your code here    int c = a ^ b;    int count = 0, tmpc = c;    if (c < 0)    tmpc = ~(c - 1) - 1;    while (tmpc)    {    int bit = tmpc & 0x1;    count = bit ? count + 1 : count;    tmpc >>= 1;    }    if (c < 0)    return 32 - count;    return count;    }};


0 0
原创粉丝点击