XOR has two magic properties: x ^ x == 0 and x ^ 0 == x. It is also commutative, so order does not matter.
Given a list where every element appears exactly twice except one, XOR-ing all elements cancels every pair and leaves the unique value. This runs in one pass with no extra memory.
Implement single_number(nums) to return the element that appears only once.
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
def single_number(nums):
"""Return the element that appears exactly once.
Every other element appears twice. XOR-ing all values cancels the pairs.
"""
# TODO: fold every value into an accumulator with XOR, starting at 0.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
XOR has two magic properties: x ^ x == 0 and x ^ 0 == x. It is also commutative, so order does not matter.
Given a list where every element appears exactly twice except one, XOR-ing all elements cancels every pair and leaves the unique value. This runs in one pass with no extra memory.
Implement single_number(nums) to return the element that appears only once.
Press Run Tests or ββ© to check your solution.