Skip to content

Commit 0f269e6

Browse files
committed
Leetcode 476
1 parent f49581e commit 0f269e6

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <iostream>
2+
#include "solution.h"
3+
using namespace std;
4+
5+
int main()
6+
{
7+
Solution s;
8+
cout << s.findComplement(76) << endl;
9+
10+
return 0;
11+
}
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
** Given a positive integer, output its complement number.
3+
** The complement strategy is to flip the bits of its binary representation.
4+
**
5+
** Note:
6+
** The given integer is guaranteed to fit within the range of a 32-bit signed integer.
7+
** You could assume no leading zero bit in the integer’s binary representation.
8+
** Example 1:
9+
** Input: 5
10+
** Output: 2
11+
** Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
12+
** Example 2:
13+
** Input: 1
14+
** Output: 0
15+
** Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
16+
*/
17+
#include <iostream>
18+
19+
using namespace std;
20+
21+
class Solution
22+
{
23+
public:
24+
/*
25+
* We need to flip each bit, but the starting position of the flip starts from the highest bit of 1,
26+
* and the front 0 cannot be flipped.
27+
* So we go from high to low traversal, if the first one is encountered, our flag is assigned to true,
28+
* and then it can be flipped.
29+
*/
30+
int findComplement(int num)
31+
{
32+
if (num == 1)
33+
return 0;
34+
35+
bool flag = false;
36+
37+
for (int i = 31; i >= 0; i--)
38+
{
39+
if(num & (1 << i))
40+
flag = true;
41+
if(flag)
42+
num ^= (1 << i);
43+
}
44+
return num;
45+
}
46+
};

0 commit comments

Comments
 (0)