LeetCode 1012 Complement of Base 10 Integer 解题报告

题目要求

Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation.

The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1.  For example, the complement of "101" in binary is "010" in binary.

For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.

题目分析及思路

给定一个十进制数N,要求返回它的二进制complement的十进制形式。某数的二进制complement是将它的1变为0,0变为1。可以先获取给定数的二进制的位数,然后将其和同位数二进制全为1的数做异或可得到最后的结果。

python代码

class Solution:

    def bitwiseComplement(self, N: int) -> int:

        n_b = bin(N)

        l = len(n_b[2:])

        return N ^ int((math.pow(2,l)-1))

        

 

转载于:https://www.cnblogs.com/yao1996/p/10550279.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值