single_number
1from functools import reduce 2 3 4# @leet start 5class Solution: 6 def singleNumber(self, nums: list[int]) -> int: 7 """ 8 In an array where each number is present twice except for one number, 9 this function finds that number. 10 The way it does this is by using xor. 11 If you xor a number by itself, you get 0. 12 So all of the numbers that show up twice reduce to 0, and the only number 13 that shows up once remains. 14 """ 15 return reduce(lambda x, y: x ^ y, nums) 16 17 18# @leet end 19 20 21def test(): 22 assert 2 + 2 == 4
class
Solution:
6class Solution: 7 def singleNumber(self, nums: list[int]) -> int: 8 """ 9 In an array where each number is present twice except for one number, 10 this function finds that number. 11 The way it does this is by using xor. 12 If you xor a number by itself, you get 0. 13 So all of the numbers that show up twice reduce to 0, and the only number 14 that shows up once remains. 15 """ 16 return reduce(lambda x, y: x ^ y, nums)
def
singleNumber(self, nums: list[int]) -> int:
7 def singleNumber(self, nums: list[int]) -> int: 8 """ 9 In an array where each number is present twice except for one number, 10 this function finds that number. 11 The way it does this is by using xor. 12 If you xor a number by itself, you get 0. 13 So all of the numbers that show up twice reduce to 0, and the only number 14 that shows up once remains. 15 """ 16 return reduce(lambda x, y: x ^ y, nums)
In an array where each number is present twice except for one number, this function finds that number. The way it does this is by using xor. If you xor a number by itself, you get 0. So all of the numbers that show up twice reduce to 0, and the only number that shows up once remains.
def
test():