0

LeetCode ^的運算

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
function singleNumber(nums) {

let sum=0;
for (let i=0;i<nums.length;i++){
sum=sum^nums[i];
}
return sum;

}

https://ithelp.ithome.com.tw/articles/10213278
>明白XOR不同為0相同為1

kekeke iT邦新手 4 級 ‧ 2020-11-12 14:28:17 檢舉

1 個回答

0

iT邦大神 1 級 ‧ 2020-11-12 14:06:04

JSFiddle執行以下程式

var arr = [10, 10, 20 , 20, 30];
console.log(singleNumber(arr));
arr = [10, 10, 20 , 30, 30];
var result = singleNumber(arr);

function singleNumber(nums) {

let sum=0;
for (let i=0;i<nums.length;i++){
sum=sum^nums[i];
console.log(i, sum);
}
return sum;

}

kekeke iT邦新手 4 級 ‧ 2020-11-12 14:18:43 檢舉

0 10
1 0
2 20
3 10
4 20

0 10 00000 01010 => 01010
1 0  01010 01010 => 00000
2 20 00000 10100 => 10100
3 10 10100 11110 => 01010
4 20 01010 11110 => 10100

kekeke iT邦新手 4 級 ‧ 2020-11-12 14:32:10 檢舉

listennn08大大寫得真好,一目了然

kekeke iT邦新手 4 級 ‧ 2020-11-12 14:34:41 檢舉

var arr = [10, 10, 20 , 20, 30];
console.log(singleNumber(arr));
arr = [10, 10, 20 , 30, 30];
console.log(singleNumber(arr));
arr = [10, 20, 20 , 30, 30];
console.log(singleNumber(arr));

function singleNumber(nums) {

let sign=1;
let sum=0;
for (let i=0;i<nums.length;i++){
sum=sum + nums[i]*sign;
sign = -1 * sign;
console.log(i, sum);
}
return sum;

}
kekeke iT邦新手 4 級 ‧ 2020-11-12 14:48:40 檢舉