C++ | Leetcode C++题解之第476题数字的补数
题目:
题解:
class Solution {
public:
int findComplement(int num) {
int highbit = 0;
for (int i = 1; i <= 30; ++i) {
if (num >= (1 << i)) {
highbit = i;
}
else {
break;
}
}
int mask = (highbit == 30 ? 0x7fffffff : (1 << (highbit + 1)) - 1);
return num ^ mask;
}
};