Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
题目给出一个正整数,要求得到它的complement number。complement number是先对原正整数取二进制,然后各位取反,最后再化为十进制的数。可以先获得原正整数的各位数,然后与1依次异或,将结果乘以权并求和。
class Solution:
def findComplement(self, num: ‘int‘) -> ‘int‘:
b = []
res = 0
while num:
b.append(num % 2)
num //= 2
for i in range(len(b)):
b[i] ^= 1
res += (b[i] * math.pow(2, i))
return int(res)
LeetCode 476 Number Complement 解题报告
原文:https://www.cnblogs.com/yao1996/p/10386871.html