---
title: 'LeetCode 476. Number Complement'
disqus: hackmd
---
# LeetCode 476. Number Complement
## Description
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
## Example
Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
## Constraints
0 <= n <= 2^31^ - 1
## Answer
此題因num都為正數,所以做右移是沒問題的,所以將num最高位以下的每個bit都填滿就可以做出mask,最後將mask做 ~num即可得答案。
```Cin=
//2022_03_13
int findComplement(int num){
int msk = num;
msk |= (msk >> 1);
msk |= (msk >> 2);
msk |= (msk >> 4);
msk |= (msk >> 8);
msk |= (msk >> 16);
return ~num & msk;
}
```
## Link
https://leetcode.com/problems/number-complement/
###### tags: `Leetcode`