Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
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
更快捷的解法为位运算:
class Solution(object):
def findComplement(self, num):
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num