LeetCode 476 Number Complement 解题报告

题目要求

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. 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)

            

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10386871.html