# 136. Single Number

### 題目敘述

Given a non-empty array of integers `nums`, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

``````Input: nums = [2,2,1]
Output: 1
``````

Example 2:

``````Input: nums = [4,1,2,1,2]
Output: 4
``````

Example 3:

``````Input: nums = [1]
Output: 1
``````

Constraints:

• `1 <= nums.length <= 3 * 10**4`
• `-3 * 10**4 <= nums[i] <= 3 * 10**4`
• Each element in the array appears twice except for one element which appears only once.

### 解法解析

#### 程式範例

##### Go
``````func singleNumber(nums []int) int {
res := 0
for _, n := range nums {
res = res ^ n
}
return res
}
``````
##### JavaScript
``````/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
let result = 0;
for (let i of nums) {
result ^= i;
}
return result;
};
``````
##### Kotlin
``````class Solution {
fun singleNumber(nums: IntArray): Int {
var result: Int = 0
for (i in nums) {
result = result xor i
}
return result
}
}
``````
##### PHP
``````class Solution
{

/**
* @param Integer[] \$nums
* @return Integer
*/
function singleNumber(\$nums)
{
\$count_nums = array_count_values(\$nums);
foreach (\$count_nums as \$key => \$value) {
if (\$value == 1) {
return \$key;
}
}
}
}
``````
##### Python
``````class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
``````
##### Rust
``````impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
let mut res = 0;
for num in nums {
res ^= num;
}
res
}
}
``````
##### Swift
``````class Solution {
func singleNumber(_ nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum ^= num
}
return sum
}
}
``````