只出现一次的数字
#算法/位运算
目录
1. 总结
var singleNumber = function (nums) {
let res = 0;
for (let num of nums) {
res ^= num;
}
return res;
};
2. 题目
3. a ^ a = 0 ; a ^ 0 = a
的运用
异或运算
的性质是需要我们牢记的:
- 一个数和它本身做
异或
运算结果为0
,即a ^ a = 0
; - 一个数和 0 做
异或
运算的结果为它本身
,即a ^ 0 = a
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
let res = 0;
nums.forEach((num)=>{
console.log(res,num);
res = res ^ num;
})
return res;
};
singleNumber([4,1,2,2,1,4,5])
0 4
4 1
5 2
7 2
5 1
4 4
0 5