476. Number Complement

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        hasCount=False
        bnum=bin(num)
        bnum=list(bnum)
        output=list()
        for bit in bnum:
            if bit=='1':
                output.append('0')
                hasCount=True
            if bit=='0' and hasCount==True:
                output.append('1')
            if bit=='0' and hasCount==False:
                output.append('0')
        return int(''.join(output),2)

Your runtime beats 0.95 % of python submissions.


这……也算是一种能力了吧

贴两个大佬的代码:
class Solution(object): def findComplement(self, num): return num ^ ((1 << num.bit_length()) - 1)
----------------------------------------------------------

class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ a = bin(num)[2:] s = '' for i in a: if i == '0': s = s + '1' if i == '1': s = s + '0' return int(s,2)

其中bin()是将int转换成二进制补码,返回一个0bxxx的字符串。类似的有oct(x)和hex(x),分别是八进制和十六进制。前缀分别为0o和0x。

join:http://www.runoob.com/python/att-string-join.html,可以将list转换为以某个字符间隔的字符串

int是int('字符串形式的数字',x进制),以十进制的形式返回一个x进制的数字
----------------------
注意,python中的二进制补码表现为,如0B1001011的形式。
问题的关键在于我想复杂了,实际上在python中,二进制会以0b1XXX的形式显示,即不显示第一个1前面的一系列0,而且题目note2也说了,
  1. You could assume no leading zero bit in the integer’s binary representation.
所以,还是要审题清楚。。

评论

此博客中的热门博文

232. Implement Queue using Stacks

496. Next Greater Element I

20. Valid Parentheses