Skip to content

Commit fc08595

Browse files
Create Day 4 Number Complement.cpp
1 parent c51d330 commit fc08595

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Day 4 Number Complement.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
PROBLEM:
2+
3+
4+
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
5+
6+
7+
8+
Example 1:
9+
10+
Input: 5
11+
Output: 2
12+
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
13+
14+
15+
Example 2:
16+
17+
Input: 1
18+
Output: 0
19+
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
20+
21+
22+
SOLUTION:
23+
24+
25+
class Solution {
26+
public:
27+
int findComplement(int num) {
28+
29+
int ans=0,j;
30+
31+
j=0;
32+
while(num>=(1LL<<j))
33+
{
34+
if(!(num & (1LL<<j)))
35+
{
36+
ans=ans|(1LL<<j);
37+
}
38+
39+
j++;
40+
41+
}
42+
43+
return ans;
44+
45+
}
46+
};

0 commit comments

Comments
 (0)