1 xor 1 = 0, 1 xor 0 = 1. So XOR operator will cancel a number if it appears twice. So this problem can be solve by xor all the numbers and the one left will be the one that appears once.
1: class Solution {
2: public:
3: int singleNumber(vector<int>& nums) {
4: int single = 0;
5: for (int n : nums) {
6: single ^= n;
7: }
8: return single;
9: }
10: };
No comments:
Post a Comment