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.
其大意是说就一个正整数的补码再做取反。
class Solution {
public:
int findComplement(int num) {
int ret = 0;
int i;
for(i = 0;num > 0; i++)
{
if(!(num&1))
ret |= 0x1 << i;
num >>= 1;
}
return ret;
}
};