【位运算-简单】476. 数字的补数

【题目】
给你一个 正 整数 num ,输出它的补数。补数是对该数的二进制表示取反。
【示例 1】
输入:num = 5
输出:2
解释:5 的二进制表示为 101(没有前导零位),其补数为 010。所以你需要输出 2
【示例 2】
输入:num = 1
输出:0
解释:1 的二进制表示为 1(没有前导零位),其补数为 0。所以你需要输出 0 。
【提示】
给定的整数 num 保证在 32 位带符号整数的范围内。
num >= 1
你可以假定二进制数不包含前导零位。
本题与 1009 https://leetcode-cn.com/problems/complement-of-base-10-integer/ 相同
【代码】
【Python】
在这里插入图片描述

class Solution:
    def findComplement(self, num: int) -> int:
        s_num=bin(num)[2:]
        ans=0
        for c in s_num:
            ans=ans*2+int(c)^1
        return ans

【写法2】
在这里插入图片描述

class Solution:
    def findComplement(self, num: int) -> int:
        s_num=bin(num)[2:]
        ans=0
        for c in s_num:
            ans<<=1
            ans+=int(c)^1
        return ans

猜你喜欢

转载自blog.csdn.net/kz_java/article/details/115095946