[LeetCode] 476.Number Complement 备忘

476. Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

求一个数字的补数,即除了高位的0,所有位上面的值相反的数字。


最容易想到的方法就是如何得到一个mask,让这个数的前面的几位高位全是0,后面的低位都是1,这样直接按位取反这个数之后和这个mask做一次位与操作就可以得到正确的结果了。所以首先让mask为0xffffffff(题目中有32位长度的限制),之后以mask & 这个数不为0为循环条件,将mask一次一次的左移一位,这样就将这个数右边所有的位都成为0,将mask按位取反之后,得到之前我们所需要的那个mask,这样即可求得这个数的补数。

class Solution {
public:
    int findComplement(int num) {
        int mask = ~0;
        
        while (num & mask)
        {
            mask <<= 1;
        }
        
        return ~mask & ~num;
    }
};


还有一个巧妙的方法,以2为底计算这个数的对数,转换为整型。以该值将1向左位移,然后减去1,作为mask。与这个数按位取反之后做位与操作得到结果。对于这个方法我的理解是,比如5的二进制为101,log2(5)的结果转换为整型是2,1左移2位,即为4,减去1为3,3的二进制为11,以该值作为mask可以得到正确的结果。同理我们发现6和7,二进制分别为110和111遵循相同的规律,即处于2^2和2^3之间,就是处于二进制1000和100之间,这些数字二进制的开头永远是第三位上的1,所以如果我们可以得到第二位置和第一位的值都是1的mask,就可以轻松算出这些数字的补数,同理其他的数字也是如此。

class Solution {
public:
    int findComplement(int num) {
       return ~num & ((1 <<(int)log2(num))-1);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值