Bitwise - XOR operation - number only appears once - given a non-empty array of integers, once, the rest of each element appears twice in addition to an element occurs only. Only to find out that there was once an element

Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.

 

Example:

Input: [2,2,1] 
Output: 1
Input: [4,1,2,1,2] 
Output: 4

GO:

func singleNumber(nums []int) int {
    var num int 
    for i := 0; i < len(nums); i++ {
         num = num ^ nums[i];
        }
        return num;
}

PHP:

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function singleNumber($nums) {
        for($i=0;$i<count($nums);$i++){
            $num = $num ^ $nums[$i];
        }
        return $num;

    }
}

  

Guess you like

Origin www.cnblogs.com/already/p/12111071.html