[Java trivia crazy] Given a non-empty array of integers, each element appears twice except for a certain element that appears only once. Find the element that appears only once.

Haha, today I did a seemingly simple question, but it's actually very ingenious

So at first, I wanted to use the concept of counters, but I found that it didn't work, and the subject conditions were a bit harsh. Finally, I suddenly thought of the ^ operator that Bo brother told me at the beginning,

It works like this

Involving the XOR operation, for this question, you should know what is the nature of the XOR

  1.  Any number that is XORed with 0 is a primitive number
  2. XOR with itself, then 0
  3. Commutative law and associative law (the key to solving this problem), you write the calculation of the entire loop as a mathematical operation process, you will find that you can use the commutative law and the associative law to achieve the requirements of this problem

So, the code and result are as follows 

Ahhh, it's so rewarding!

    public static void main_func(String[] args) {
          int[] array = {1,2,2,1,5,4,5};
        System.out.println(func(array));
    }
    public static int func (int[] array){
        int num=0;
        for(int i=0;i<array.length;i++){
            num^=array[i];
        }
        return num;
    }
}

Hope it helps mate

Thanks for reading~

Guess you like

Origin blog.csdn.net/qq_63511424/article/details/123698294