136. Single Number leetcode solution in c++
int singleNumber(vector<int>& nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
Explanation:
- We start by initializing the variable result
to 0. This variable will store the single number that appears only once in the given vector of integers.
- We iterate through each number num
in the nums
vector using a range-based for loop.
- Inside the loop, we use the XOR (^) operator to update the result
variable. The XOR operation returns 1 if the corresponding bits of two operands are different, and 0 otherwise. By XORing all the numbers in the vector, the duplicate numbers will cancel each other out, leaving only the single number in the result
variable.
- Finally, we return the result
variable, which now contains the single number that appears only once in the given vector.
Example:
Suppose we have the input vector nums = {2, 3, 2, 4, 4}
. We can visualize the XOR operation for each number in the vector as follows:
0 ^ 2 = 2
2 ^ 3 = 1
1 ^ 2 = 3
3 ^ 4 = 7
7 ^ 4 = 3
The final value of result
is 3, which is the single number that appears only once in the vector.