Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 092f15b

Browse files
committed
Solution added.
1 parent 63cadcb commit 092f15b

File tree

1 file changed

+50
-0
lines changed
  • 30 Days of October Challange/Week 1/5. Complement of Base 10 Integer

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation.
3+
4+
The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary.
5+
6+
For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.
7+
8+
9+
10+
Example 1:
11+
12+
Input: 5
13+
Output: 2
14+
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
15+
Example 2:
16+
17+
Input: 7
18+
Output: 0
19+
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
20+
Example 3:
21+
22+
Input: 10
23+
Output: 5
24+
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
25+
26+
27+
Note:
28+
29+
0 <= N < 10^9
30+
This question is the same as 476: https://leetcode.com/problems/number-complement/
31+
"""
32+
33+
34+
class Solution:
35+
def dec_bin(self, N):
36+
if N == 0:
37+
return '0'
38+
final = ''
39+
while N > 0:
40+
final += str(N % 2)
41+
N = N // 2
42+
return reversed(final)
43+
44+
def complement(self, s):
45+
return ''.join(['1' if char == '0' else '0' for char in s])
46+
47+
def bitwiseComplement(self, N: int) -> int:
48+
binary = self.dec_bin(N)
49+
binary_complement = self.complement(binary)
50+
return int(binary_complement, 2)

0 commit comments

Comments
 (0)