Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
一个数求补数,用二进制表示,每位取反。
1.找到该数在32位时第一个非零位,开始取反。
class Solution {
public:
int findComplement(int num) {
int i;
bool target = false;
for (i=31;i>=0;i--)
{
if((1<<i)&num)
target = true;
if (target)
num = num ^ (1<<i);
}
return num;
}
};
2.官方的solution:
用mask来求出该数的实际有效位。
class Solution {
public:
int findComplement(int num) {
unsigned mask = ~0;
while (num & mask) mask <<= 1;
return ~mask & ~num;
}
};