476. Number Complement
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- 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;
}
};
class Solution {
public:
int findComplement(int num) {
return ~num & ((1 <<(int)log2(num))-1);
}
};