解题思路:
求一个数的补数,其实就是将这个数与该数的二进制尾数相同但是所有位都是1的数异或,这样的结果刚好是该数的补数,代码如下:
class Solution {
public:
int findComplement(int num) {
int temp = 1;
while(temp < num) {
temp <<= 1;
temp += 1;
}
return num ^ temp;
}
};