LeetCode-476. Number Complement

发布于 2017-07-10 14:30:52

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.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

这个题的意思就是给一个十进制整数,然后转换成二进制,对二进制取反,然后再转换成整数。

刚开始用bin(~num)完成取反,但是好像不对,想了想还不如简单粗暴,直接对bin(num)转换后对字符串进行替换,把1替换成2,然后再把0替换成1,再把2替换成0,比如例子中对101,先replace("1","2") 变成202,然后再replace("0","1")变成212,最后再replace("2","0"),变成010,用int('010',2)转换成十进制,就是2.

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        x = bin(num)[2:].replace('1','2').replace('0','1').replace('2','0')
        return int(x,2)