1
  1. I found out that in python, if you use bin:

    >>> bin(4)
    '0b100'  
    >>> bin(-4)
    '-0b100'
    
  2. but if you try this:

    -4 >> 8 => -1
    

in fact, when right shift more than 3 bits, the answer is always -1. I know this is implementation stuff, but I came across this problem:

In the following array, find out the number which appears only once, while others appears always three times

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

This is the code

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

the answer should be -4, but instead I get 11111111111111111111111111111100; how can I convert it into -4?

1 Answer 1

3

Bit manipulation on Python are easily done with int.from_bytes and int.to_bytes.

On the other hand, solving the "find the value appearing x times" is easily solved using the Counter class:

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

Using from_bytes and to_bytes is clear and readable, so you don't want to try to do the conversion yourself.

Using Counter is also more readable than your cryptic implementation, yet my one-liner may not be the most readable imaginable version, it's still a single line and far more readeable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.