476. 数字的补数

链接

https://leetcode.cn/problems/number-complement/description/

思路

没啥好说的,二进制与十进制的互相转换,基本功。

代码

class Solution:
    def findComplement(self, num: int) -> int:
        bin_li = self.int2bin(num)
        bin_li = self.reverse(bin_li)
        return self.bin2int(bin_li)

    def bin2int(self, bin_li):
        res = 0
        for i in range(len(bin_li)):
            ex = len(bin_li)-1-i
            res += int(bin_li[i]) * pow(2, ex)
        return res

    def int2bin(self, num):
        res = []
        while num != 0:
            res.append(num % 2)
            num = num // 2
        return res[::-1]

    def reverse(self, bin_li):
        res = []
        for i in bin_li:
            if int(i) == 1:
                res.append(0)
            else:
                res.append(1)
        return res

 

posted @ 2023-09-04 13:48  BJFU-VTH  阅读(6)  评论(0编辑  收藏  举报