★136. Numbers that appear only once (bit operations)

136. Numbers that appear only once

The main knowledge points examined in this question arebit operations (here is XOR)
If the space complexity is not required, the space complexity is O(1) , there are many ways. But there is such a requirement here.
can be achieved by bit operation .

The XOR operation ⊕ has the following three properties:

  1. If any number is XORed with 0, the result will still be the original number, that is, a⊕0=a.

  2. If any number is XORed with itself, the result is 0, that is, a⊕a=0.

  3. The XOR operation satisfies the commutative law and associative law, that is, a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b.

  4. XOR with 0 as itself.
    Insert image description here

  5. XOR with itself is 0
    Insert image description here

  6. Satisfy the commutative law and associative law
    Insert image description here

Consider this question

So in this question, there are a total of 2n+1 numbers, n numbers appear twice, and 1 number appears once. So XOR ⊕ all these 2n+1 numbers, the final result is the number that only appears once.

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        int res = 0;
        for(int num:nums){
    
    
            res ^= num;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_45895217/article/details/134781715