> For the complete documentation index, see [llms.txt](https://hannahpun.gitbook.io/leetcode-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hannahpun.gitbook.io/leetcode-note/math/136-single-number.md).

# # 136 Single Number

[LeetCode](https://leetcode.com/problems/single-number/)

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

Note:
Your algorithm should have a linear runtime complexity. 
Could you implement it without using extra memory?

input: 一個雙倍出現的數字 + 單獨出現的數字組成陣列
output: 找出那個落單的
```

```
Example 1:

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

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


/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function(nums) {}
```

### 怎麼解

第一想法就是先排序後再找旁邊的是不是跟你一樣，不一樣就是落單的數字了。但後來看[這篇](https://ithelp.ithome.com.tw/articles/10158350)\
發現用 bitwise operators 可以超快。應用到 ^ 的特性。這題說是兩兩數字出現所以很適合用

**^ (XOR)**&#x20;

bit1 ^ bit2 : 當兩個位元一樣時回傳0，不一樣時回傳1。

```
     9 (base 10) = 1001 (base 2)
    14 (base 10) = 1110 (base 2)
                --------------------------------
14 ^ 9 (base 10) = 0111 (base 2) = 7 (base 10)
```

* 交换律：a ^ b ^ c  <=> a ^ c ^ b
* 任何数于0异或为任何数 0 ^ n => n
* 相同的数可以等於 0: n ^ n => 0

```
var singleNumber = function(nums) {
    let result = nums[0];
    for(let i= 1; i< nums.length; i++){
        result = result ^ nums[i]
    }
    return result;
};

console.log(singleNumber([4,1,2,1,2,2]))
```

```
所以  [4,1,2,1,2]
    4 ^ 1 ^ 2 ^ 1 ^ 2
==  1 ^ 1 ^ 2 ^ 2 ^ 4
==  0 ^ 0 ^ 4
==  4 // 答案
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hannahpun.gitbook.io/leetcode-note/math/136-single-number.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
