Code Explanation:
Function Definition
def single_number(nums):
This line defines a function called single_number.
It takes one parameter: nums, which is a list of integers.
Initialize Result Variable
result = 0
Initializes a variable result to 0.
This will store the final answer using the XOR operation.
Iterate Over All Numbers
for n in nums:
This starts a loop to go through each number n in the input list nums.
Bitwise XOR Operation
result ^= n
^= is a bitwise XOR assignment operator.
It means: result = result ^ n
XOR has some important properties:
a ^ a = 0 (a number XOR itself is zero)
a ^ 0 = a (a number XOR zero is the number itself)
XOR is commutative and associative, so order doesn't matter.
So, pairs cancel each other out, and the number that appears only once remains.
Return the Result
return result
After looping through all numbers, result holds the number that appears only once.
This line returns that number.
Function Call and Output
print(single_number([4, 1, 2, 1, 2]))
Calls the function with the list [4, 1, 2, 1, 2]
The numbers 1 and 2 appear twice, so they cancel out.
Only 4 appears once, so the output will be:
4
Final Output
4


0 Comments:
Post a Comment