Skip to content

Commit 0d7040a

Browse files
committed
Adding More Efficient Solution - Problem - 4 - Number Complement
1 parent 7fe7b09 commit 0d7040a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
##==================================
2+
## Leetcode May Challenge
3+
## Username: Vanditg
4+
## Year: 2020
5+
## Problem: 4
6+
## Problem Name: Number Complement
7+
##===================================
8+
#
9+
#Given a positive integer, output its complement number.
10+
#The complement strategy is to flip the bits of its binary representation.
11+
#
12+
#Example 1:
13+
#
14+
#Input: 5
15+
#Output: 2
16+
#Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010.
17+
#So you need to output 2.
18+
#
19+
#Example 2:
20+
#
21+
#Input: 1
22+
#Output: 0
23+
#Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0.
24+
#So you need to output 0.
25+
class Solution:
26+
def findComplement(self, nums):
27+
tmp = bin(nums) #Initialize tmp and set to binary of nums
28+
result = "".join(['0' if i == '1' else '1' for i in tmp[2:]]) #Initialize result and set 0 to 1 and 1 to 0
29+
return int(result, 2) #Return decimal representation of the result

0 commit comments

Comments
 (0)