Find a special number in an array

后端 未结 9 1643
天命终不由人
天命终不由人 2020-12-25 09:07

There are many numbers in an array and each number appears three times excepting for one special number appearing once. Here is the question: how can I find the special numb

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-25 09:46

    I didnt find the implementation of bitwise mod 3 very intuitive so I wrote a more intiuitive version of the code and tested it with various examples and it worked. Here is the code inside the loop

    threes=twos&x //=find all bits counting exactly thrice
    x&=~threes    //remove the bits countring thrice from x as well as twos
    twos&=~threes
    
    twos|=ones&x //find all bits counting exactly twice
    x&=~twos  //remove all bits counting twice from modified x as well as ones
    ones&=~twos
    
    ones|=x //find all the bits from previous ones and modified x
    

    Hope you guys find it easy to understand this version of code.

提交回复
热议问题