# 136. Single Number

## 1.問題&#x20;

* 給予一個整數(正, 負)序列, 每個數字重複2次, 找出只有出現一次的數字

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNXckvOPwfqYEo2Ylft%2F-LNXoud0XXDZuNu5qHhL%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-29%20%E4%B8%8A%E5%8D%888.56.09.png?alt=media\&token=0e1b1246-0cdf-4ab1-81bb-0b190ee6e992)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問: 是否會包括負數？
* function header, parameter
* test input
* 觀察
  * 由於最多出現兩次, 應該要想到用XOR, 當同一個bit的值皆為1或0時, 會設為0, 也就是當該bit被設兩次時, 數值會為0
* 說明想法
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        
        int res = 0;
        for (int i = 0; i < nums.size(); i++) {
            res ^= nums[i];
        } 
        
        return res;
    }
};
```


---

# Agent Instructions: 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://jenhsuan.gitbook.io/algorithm/leetcode/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.
