---
# System prepended metadata

title: \#476 Number Complement
tags: [leetcode, leetcode-easy]

---

# \#476 Number Complement
## *給定一十進位數num, 回傳該數的2的補數(十進位)*
## Log
 - build 20210905 by syhuang

## 參考解
 - 為求得num在二進位的實際位數, 先令mask為二進位數所有位數都是1
 - 跑迴圈做num&mask直到=0為止
 - 運算(~num & ~mask)極為解答
 - leetcode submit runtime 61%, memory 42%
```javascript=
var findComplement = function(num) {
    let mask = ~0;
    while(num & mask) mask <<=1;
    return ~num & ~mask;
};
```
## 初見
 - 以迴圈base=2^p與num做AND運算, 每次p++直到base>num為止
 - 把每次AND運算後=0的結果加總(做補數,因此1變0,0變1)
 - leetcode submit runtime 33%, memory 30%
```javascript=
var findComplement = function(num) {
    let base = 1, p = 0;
    let result = 0;
    while(base<num){
        if(!(num&base)) result+=base;
        base = Math.pow(2,++p);
    }
    return result;
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/number-complement/discuss/96017/3-line-C%2B%2B)
###### tags: `leetcode`, `leetcode-easy`