---
# System prepended metadata

title: \#268 Missing Number
tags: [leetcode, leetcode-easy]

---

# \#268 Missing Number
## *給定一存有"不小於0的連續整數"的陣列, 找出缺少的數字(隨機排列,每個數字只會出現1或0次)*
## Log
 - build 20210605 by syhuang

## bit運算
 - 利用XOR運算會將兩相同數字抵銷的特性, 用迴圈跑一次陣列, 迭代運算i^num[i], 最後的結果再運算一次^i, 就可以得到缺少的數字
```javascript=
var missingNumber = function(nums) {
    var result = 0;
    for(var i=0; i<nums.length; i++){
        result ^= (nums[i] ^ i);
    }
    return result ^ nums.length;//因為範圍是[0,i],最後要再運算一次i
};
```
## 初見
 - 單純用javascript原生方法解,時間複雜度較高(O(n^2))
```javascript=
var missingNumber = function(nums){
    var result;
    for(result=0;result<nums.length;result++){
        if(nums.indexOf(result)==-1) break;
    }
    return result;
};
```
## 備註
 - XOR特性運用在數字兩兩消除
## 參考
 - [參考解](https://leetcode.com/problems/missing-number/discuss/69791/4-Line-Simple-Java-Bit-Manipulate-Solution-with-Explaination)
###### tags: `leetcode`, `leetcode-easy`