Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
这一题的意思就是给你一个在int范围内的数,让你求它的补码。当然请注意此题的补码不是你计组里学的那个补码,所以想直接求反加一是不行的。
此题两种解法,第一种自然就是暴力解:
class Solution(object):
def findComplement(self, num):
binary = bin(num)[2:]
ans = 0
for i, u in enumerate(binary[::-1]):
if u == '0':
ans += 2 ** i
return ans
由于使用bin函数转十进制为二进制,得到的是一个0b开头的数字,所以取[2:]得到纯数字,用[::-1]翻转列表。
更快捷的解法为位运算:
class Solution(object):
def findComplement(self, num):
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num