在Python中将带符号的二进制数转换为整数

时间:2016-06-02 20:12:39

标签: python bit-manipulation

  1. 我发现在python中,如果你使用bin

    >>> bin(4)
    '0b100'  
    >>> bin(-4)
    '-0b100'
    
  2. 但如果你试试这个:

    -4 >> 8 => -1
    
  3. 实际上,当右移3位以上时,答案总是-1。我知道这是实现的东西,但我遇到了这个问题:

    在以下数组中,找出仅出现一次的数字,而其他数字总是出现三次

    [-2,-2,1,1,-3,1,-3,-3,-4,-2]
    

    这是代码

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if nums == None:
                return None
            ans = 0
            for i in range(32):
                numOfI = 0
                for num in nums:
                    if (( num >> i) & 1) == 1 :
                        numOfI += 1
                        numOfI %=3
                print i,numOfI
                if numOfI != 0:
                    ans = ans + (numOfI << i)
            return ans
    

    答案应为-4,而是11111111111111111111111111111100;我该如何将其转换为-4?

1 个答案:

答案 0 :(得分:3)

使用int.from_bytesint.to_bytes可以轻松完成Python上的位操作。

另一方面,使用x类可以轻松解决“找出值Counter次”的问题:

>>> from collections import Counter
>>> values = [-2,-2,1,1,-3,1,-3,-3,-4,-2]
>>> [value for value, count in Counter(values).items() if count == 1]
[-4]

使用from_bytesto_bytes清晰可读,因此您不想尝试自行进行转换。

使用Counter也比你的神秘实现更具可读性,但我的单行可能不是最易读的可想象版本,它仍然是单行并且更易于翻译。

相关问题