[Title]
Give you a positive integer num and output its complement. The complement is the inverse of the binary representation of the number.
[Example 1]
Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (without leading zero), and its complement is 010. So you need to output 2
[Example 2]
Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (without leading zero), and its complement is 0. So you need to output 0.
[Hint] The
given integer num is guaranteed to be within the range of 32-bit signed integers.
num >= 1
You can assume that the binary number does not contain leading zeros.
This question is the same as 1009 https://leetcode-cn.com/problems/complement-of-base-10-integer/
[Code]
[Python]
class Solution:
def findComplement(self, num: int) -> int:
s_num=bin(num)[2:]
ans=0
for c in s_num:
ans=ans*2+int(c)^1
return ans
【Writing 2】
class Solution:
def findComplement(self, num: int) -> int:
s_num=bin(num)[2:]
ans=0
for c in s_num:
ans<<=1
ans+=int(c)^1
return ans