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))

        

 

posted on 2019-03-18 09:18  锋上磬音  阅读(243)  评论(0编辑  收藏  举报