Leetcode 476. Number Complement

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Number Complement

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int findComplement(int num) {
int result = 0;
stack<int> s;
while(num) {
int bit = num & 1;
num >>= 1;
s.push(bit);
}
while(!s.empty()) {
result <<= 1;
int bit = s.top();
s.pop();
result |= (bit ^ 1);
}
return result;
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int findComplement(int num) {
int mask = ~0;
while (num & mask) {
mask <<= 1;
}
return ~mask & ~num;
}
};

Reference

  1. https://leetcode.com/problems/number-complement/description/
如果有收获,可以请我喝杯咖啡!