LeetCode/solutions/476. Number Complement.md

16 lines
460 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [476. Number Complement](https://leetcode.com/problems/number-complement/description/)
# 思路
先将num的bit全部翻转再看num有多少前导0然后用一个合适的mask对之前的翻转结果进行与操作即可。
# C++
``` C++
class Solution {
public:
int findComplement(int num) {
if(num == 0) return 1;
int i, res = ~num, mask=0xffffffff;
while(mask & num) mask <<= 1;
return res & ~mask;
}
};
```