(Learn more about XOR) Two sample questions about XOR (interview questions)

topic

An array, (1) Only one value has an odd number of occurrences, and all other numbers have an even number of occurrences. Find this number. (2) There are two numbers in the array with odd numbers of occurrences, and the remaining numbers are even numbers of occurrences. Find these numbers.

problem solving (1)

  • analyze 

According to the nature of XOR, the XOR of the same value is equal to 0. As long as the entire array is XORed, the last even-numbered number will be returned to 0, leaving only odd-numbered numbers.

  • Operation code (Java)
public void tatic Num1(int[] arr){
int eor = 0 ;
for(int i =0 ;i<arr.length;i++){
eor ^= arr[i];
}
system.out.println(eor)
}

problem solving (2)

  • analyze

Same as (1), when we XOR the entire array, we get eor=a^b (the XOR result variable is defined here as eor) and the rest is two numbers that appear odd times XOR each other a^b .

We can think like this, the values ​​of these two numbers are different, then their XOR result is not zero, that is to say, they must be different in a certain bit, and a certain bit with XOR result must be 1. Then we find the position of this 1, and then go to the whole array to filter again, all the numbers that are 1 in this bit are XORed, and the final result must be one of a and b, and then use it to XOR the previous eor to get another number.

  • Operation code (Java)

public void static Num2(int[] arr){
int eor = 0 ;
for(int i =0 ;i<arr.length;i++){
eor ^= arr[i];
}
 onlyone = 0
 rightone = eor&(~eor-1)//找到这个数最右边的1
for(int i = 0;i<arr.length;i++){
if(arr[i]&rightone == 0 ){
onlyone ^=arr[i]
}
}
system.out.println(eor+""+(onlyone^eor))
}
  • How to find the rightmost 1 of this number

 It is often used when writing code, the following is to find the rightmost of the number

rightone = eor&(~eor-1)

Guess you like

Origin blog.csdn.net/qq_48860282/article/details/123596922