1. Description
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 in its binary representation.
- For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
constraints :
- 1 <= num < \(2^{31}\)
2. Algorithms
To change each bit into complement in its binary representation, we have to chage "1" to "0" and "0" to "1".
- Start
- Declare variable binary_rep and initialize it with binary representation of input num.
- Repeat the steps through the element of binary_rep.
- If current bit is "1", update current bit with "0".
- Else, update current bit with "1".
- Return the result after changing binary representation to integer.
- End
3. Codes
class Solution:
def findComplement(self, num: int) -> int:
# Store binary representation of input num.
binary_rep = list(bin(num))[2:]
print(binary_rep)
for i in range(len(binary_rep)) :
if binary_rep[i] == "1" :
binary_rep[i] = "0"
else :
binary_rep[i] = "1"
return int("".join(binary_rep), 2)
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
485 Max Consecutive Ones (0) | 2022.08.31 |
---|---|
482 License Key Formatting (0) | 2022.08.31 |
463 Island Perimeter (0) | 2022.08.31 |
461 Hamming Distance (0) | 2022.08.30 |
459 Repeated Substring Pattern (0) | 2022.08.30 |