On the operator ^ problem

topic description

given a sequence containing n numbers of 0, 1, 2,., n, find 0. The number in n that does not appear in the sequence.

related codes

var missingNumber = function(nums) {
    var res = nums.length;
    
    for(var i = 0; i < nums.length; iPP){
        res = res^(i ^ nums[i]);
    }
    
    return res;
};

see a great god"s answer, but do not quite understand the meaning of res = res ^ (I ^ nums [I]); , check the explanation of ^, debug the program, still do not quite understand how to compare it, please answer, thank you

Mar.30,2022

Bitwise_Operators-sharp

var missingNumber = function(nums) {
    var res = nums.length;
    
    for(var i = 0; i < nums.length; iPP){
        res = res^(i ^ nums[i]);
    }
    
    return res;
};

first of all, XOR does not need to control the order.
assume that the array is a continuous [1meme2... code n] array, then nums.length must be equal to some value in the array, that is, n ^ nums.length is 0 , because x ^ 0 is x , so if the data is continuous, there must be nFel.1 with the same logic as the appeal process.

The final result is length XOR each value XOR subscript , that is, 3 ^ 3 ^ 2 ^ 0 ^ 2 .

PS: personal use of such code is not recommended


has two main properties:

  1. XOR satisfies the commutative law;
  2. two bits XOR, 0 if the same, 1 if the difference.

simplify the problem, for example, given the array [0, 1, 2, 3, 5], it is missing a 4, and now we need to find 4.

  https://subetter.com/articles.... 

A bit more powerful, refer to the book "algorithms to learn the Mysteries of efficient algorithms", which is almost out of print and brain-burning.

Menu