题目要求
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.
题目分析及思路
题目给出一个正整数,要求得到它的complement number。complement number是先对原正整数取二进制,然后各位取反,最后再化为十进制的数。可以先获得原正整数的各位数,然后与1依次异或,将结果乘以权并求和。
python代码
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)