Preface
In order to improve efficiency when brushing Leetcode, many operations can be optimized using bit operations. This article is used to collect and summarize the related operations of bit operations. The basic knowledge of bit operations can be seen: the portal .
content
Realize the four arithmetic
This is too hard core, and look on the line, and if writing code so that it would be too exaggerated !! Fight (O - ) ~ '' ☆ ☆ ミ ミ
Plus one operation
Conventional code:
int a = 1;
a += 1;
Bit operation code:
int a = 1;
a = -~a;
Minus one operation
int a = 1;
a -= 1;
Bit operation code:
int a = 1;
a = ~-a;
Multiply by 2 operation
This operation can be performed as long as it is multiplied by the power of 2, and it is shifted to the left as much as the power of 2 is multiplied.
Conventional code:
b = a * 2;
Bit operation code:
b = a << 1;
Multiply by 2 and add 1 operation
Conventional code:
b = a * 2 + 1;
Bit operation code:
b = a << 1 | 1;
Divide by 2 operation
This operation can be performed as long as it is divided by the power of 2, and it is shifted to the right as much as the power of 2 is divided.
Conventional code:
b = a / 2;
Bit operation code:
b = a >> 1;
Remainder (modulo) operation
Note: The divisor must be a power of 2.
Conventional code:
a = a % 4;
Bit operation code:
a = a & (4 - 1);
Determine parity
Conventional code:
if(a % 2);//奇数
if(!(a % 2));//偶数
Bit operation code:
if(a & 1);//奇数
if(!(a & 1));//偶数
Swap two numbers
Conventional code:
int a = 1,b = 2,temp;
temp = a;
a = b;
b = temp;
Bit operation code:
int a = 1,b = 2;
a ^= b;
b ^= a;
a ^= b;
Case conversion
In fact, this is not magic!
Use or operation |
and to 空格
convert English characters to lowercase
('a' | ' ') = 'a';
('A' | ' ') = 'a';
Use the AND operation &
and to 下划线
convert English characters to uppercase
('b' & '_') = 'B'
('B' & '_') = 'B'
Using the XOR operation ^
, and 空格
for English characters invert case
('d' ^ ' ') = 'D'
('D' ^ ' ') = 'd'
XOR
XOR (^)
- If we do the ^ operation on 0 and binary, we still get this binary bit.
0 ⨁ 0 = 0, 0 ⨁ 1 = 1 0 \bigoplus 0 = 0,0 \bigoplus 1 = 10⨁0=0,0⨁1=1 - If we do the ^ operation on the same binary, the result returned is 0
1 ⨁ 1 = 0, a ⨁ a = 0 (a 1 \bigoplus 1 = 0,a \bigoplus a = 0(a1⨁1=0,a⨁a=0 ( a can be any number))) - ^Satisfy the commutative and associative laws
a ⨁ b ⨁ a = (a ⨁ a) ⨁ b = 0 ⨁ b = ba \bigoplus b \bigoplus a = (a \bigoplus a) \bigoplus b = 0 \bigoplus b = ba⨁b⨁a=(a⨁a)⨁b=0⨁b=b
Related leetcode topics:
136. The number that appears only once
389. Find the difference
data
Bit arithmetic means multiply by 2 and multiply by 2+1
algorithm articles: Basic
bit arithmetic operations Bit Twiddling Hacks
postscript
Continually updated!