File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Leetcode-May-Challenge/Day - 4 Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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 = nums #Initialize tmp to nums
28+ bit = 1 #Initialize bit to 1
29+ while tmp : #Loop
30+ num = num ^ bit #Update num by taking XOR of num and bit
31+ bit = bit << 1 #Taking left shift by 1 for bit
32+ tmp = tmp >> 1 #taking right shift by 1 for tmp
33+ return num #We'll return our number
You can’t perform that action at this time.
0 commit comments