Single Number: others appear twice, return the lone value.
def single_number(nums):
result = [1]
for x in nums:
result [2] x
return resultShow answer
Answer
def single_number(nums):
result = 0
for x in nums:
result ^= x
return result- Gap 1 is
0. Not1: XOR starts from 0, its identity, and a start of 1 flips the lowest bit of the answer. Notnums[0]: The loop also visits nums[0], so it is XORed in twice and cancels out. - Gap 2 is
^=. Not+=: A sum keeps the pairs, so they never cancel to leave the single value. Not|=: OR never clears a bit, so pairs cannot cancel each other.