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.
最开始的实现方法:
int findComplement(int num)
{
for(int i=1;i <= num;i <<= 1)
num ^= i;
return num;
}
提示有未通过的用例,上面的思路其实是正确的,num中的每一位与1异或,通过左移i实现num的每一位与1相异或.问题的原因在于32位正数的最大值是2的31次方-1即2147483647,在上述循环中,当i的值为1073741824即2的30次方,此时num的值已经变为了0,然后i再左移一位就变成了-2147483648,因此<=num条件成立,所以将i声明为long,或者循环条件中修改为(i<=num)&&(i>0)两种方法都可以。
int findComplement(int num)
{
for( long i=1;i <= num;i <<= 1)
num ^= i;
return num;
}