Js algorithm puzzle

given a non-empty array of integers, each element appears twice except for an element that appears only once. Find the element that only appears once.

example 1:

: [2,2,1]
: 1

example 2:

: [4,1,2,1,2]
: 4

the answer with the highest running efficiency

var singleNumber = function(nums) {
    return nums.reduce((acc, num) => acc^num, 0)
};

I don"t understand why a ^ can calculate the value. Can you explain the operation?

Mar.18,2021

this is the XOR operation , that is, 1 ^ 0 = 1, 1 ^ 1 = 0,0 ^ 0 = 0. Different together is 1, the same together is 0. This is easy to explain, since the array appears in pairs, then after they are converted to binary, they must directly cancel out to zero, leaving only the single element. Since no displacement has occurred, there is a way to revert to the original value

provides a quick way to convert to binary: (Number) .toString (2)
for example, the binary of 5 is: (5) .toString (2) = '101'
you calculate these binaries and cancel each other out

then the last zero can not be added, and it can be traversed less

.

I think if you don't even know the operation, you should first know reduce , and know that the second parameter is only the initial value and is only useful for the first time. So to restore the process is, 0 ^ 2 = 2, 2 ^ 2 = 0,0 ^ 1 = 1, maybe you understand. If you don't even understand bitwise, then I suggest you read the basics of programming, otherwise your progress will always be slow.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b74d-2b5fa.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b74d-2b5fa.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?