Record some clever bit operations

Top top top top top top top top top top top top top top top top

Summary of bit operation skills (continuous update...)

1. Number 3 that only appears once

Using XOR operation can help us eliminate numbers that appear twice

x & (-x)  is the rightmost 1 in the reserved bits and the other 1 is set to 0.

Two, 191. The number of bits 1

(When x is not 0) x & (x-1)  is a method to change the rightmost 1 to 0 and keep the rest of the bits unchanged.

In addition:

Change the first 0 from the right to 1: x or (x+1)

Turn the consecutive 1s on the right into 0: x and (x+1)

Change the consecutive 0s on the right to 1: x or (x-1)

 

image.png

3. Set a certain position to 0 or set it to 1 or negate it

Set the i-th position of x (counted from the right) to 1, x=x | (1<<(i-1))

Set the i position of x (counting from the right) to 0, x=x & !(1<<(i-1))

Invert the i-th position of x (counting from the right), x=x ^ (1<<(i-1))

Guess you like

Origin blog.csdn.net/hbhhhxs/article/details/107982514