1 classSolution {2 Public:3 intSinglenumber (intA[],intN) {4 intBITS =sizeof(int)*8;5 intresult=0;6 for(intI=1; i<=bits; i++)7 {8 intw=0;9 intt=1;Ten One for(intj=0; j<n; J + +) AW + = (a[j]>> (i-1)) &T; -result+= (w%3) << (I-1); //If the other number repeats K times except for one number, change the 3 here to K - } the returnresult; - } -};
Using binary bitwise operations to solve this problem, such as the input array is [2,2,3,2]
They correspond to the binary as:
0010 (2)
0010 (2)
0011 (3)
0010 (2)
————
Corresponding bit sum: 0 0 4 1
Add all the integers corresponding to the bits and divide the remainder after 3 to get 0011 (3), which is the single number we are looking for.
For all but one occurrence of an integer, the other integers appear k times (k=2,3,4 ...), ask for a single number, or you can use the above bit arithmetic to solve the problem, just change the program 3 to K.