LeetCode: Bit Manipulation Originally published in Chinese on 2019-06-19; this English edition preserves the original scope and technical context.
Bit operations include:
with & or | XOR ^ Negation ~ Move left « Move right » Tips Shift operation
x « 1: arithmetic left shift All bits in the binary representation of a number are shifted one position to the left, which is equivalent to multiplying by 2 pad 0 on the right x » 1: arithmetic right shift All bits in the binary representation of a number are shifted one position to the right, which is equivalent to dividing by 2 Complement the sign bit on the left, that is, complement 0 for positive numbers, and complement 1 for negative numbers (based on the two’s complement code) negative shift Negative numbers are stored in the form of two’s complement. When a negative number is shifted to the right, it needs to be inverted and converted into its complement, plus one to convert it into its complement, then moved to the right one bit to get a new complement, then subtracted by one to get a new one’s complement, and then inverted and converted into the original code to get the result. For example, the binary representation of -7 is 10000111 (because 32 bits are too long, so an 8-bit int is used here), its complement is 11111000, and its complement is 11111001. Moving one position to the right is 11111100, and subtracting one gets the new complement 11111011. The original code is 10000100, that is -4; shifting the complement one bit to the left is 11110010, subtracting one to get the new complement 11110001, the original code is 10001110, which is -14 A simpler way to understand is to multiply left shift by 2 and right shift by 2. For example -7 » 1 = -7 / 2 = -4, -7 « 1 = -14 Title 1. Single number 693 alternating bits binary number Checks whether two adjacent digits of a binary number are not equal.
...