Simple Python Bit Manipulate Solution


  • 0
    L

    Following the explanation in this java solution. To quote, "The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number. In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number."

        def missingNumber(self, nums):
            xor = 0
    
            for i, e in enumerate(nums):
                xor = xor ^ i ^ e
            
            return xor ^ len(nums)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.