Skip to content

Commit b716f53

Browse files
committed
Complement of Base 10 Integer
1 parent c185347 commit b716f53

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

1009-complement-of-base-10-integer.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/complement-of-base-10-integer/
3+
4+
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
5+
in its binary representation.
6+
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
7+
Given an integer n, return its complement.
8+
9+
Example 1:
10+
Input: n = 5
11+
Output: 2
12+
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
13+
14+
Example 2:
15+
Input: n = 7
16+
Output: 0
17+
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
18+
19+
Example 3:
20+
Input: n = 10
21+
Output: 5
22+
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
23+
24+
Constraints:
25+
0 <= n < 109
26+
"""
27+
# Time Complexity: O(logN)
28+
class Solution:
29+
def bitwiseComplement(self, n: int) -> int:
30+
mask = 1
31+
32+
"""
33+
(number) => (how-number-is-derived)=>binary-string
34+
mask = 1 => 1 => 1
35+
mask = 3 => (2*1 + 1) => 11
36+
mask = 7 => (3*2 + 1) => 111
37+
mask = 15 => (7*2 + 1) => 1111
38+
"""
39+
while mask < n:
40+
mask = mask * 2 + 1
41+
42+
return mask ^ n

0 commit comments

Comments
 (0)