What functions can bitwise Operations implement?
What functions can bitwise Operations implement?
In many cases, bitwise operations are recommended to reduce the time complexity of the algorithm. Today, let's sort out the functions that bitwise operations can implement.
1. multiplication and division 2
Shift 1 to 2 and shift n to 2 to 2;
Shift 1 to 2 and shift n to 2 to 2;
For example:
# Include <iostream> using namespace std; int main () {int a = 16; int B = 25; // multiply by 2 cout <(B <1) <''<(a> 1) <endl; return 0 ;}
2. Determine the parity
Use bitwise AND and 1 bitwise AND in place operations.
As follows:
# Include <iostream> using namespace std; int main () {int a = 16; int B = 25; // judge the parity if (a & 1) cout <"Odd" <endl; elsecout <"Even" <endl; return 0 ;}
3. remainder operation
We still use the bitwise AND operator, but it is no longer a bitwise AND.
# Include <iostream> using namespace std; int main () {int a = 16; int B = 25; // obtain cout <(a & 3) <endl; // cout divided by the remainder of 4 <(a & 7) <endl; // divided by the remainder of 8 <(a & 8) <endl; // invalid, returns 0 ;}
Analysis: note that this method can only calculate the remainder of the power of 2, and the result of bitwise AND can only be 2 ^ n-1, because the binary form of these numbers is 1.
4. Calculate the inverse number
Use bitwise inverse operators.
// Calculate the opposite number cout <(~ A + 1) <endl;
5. Calculate the absolute value using the XOR operator (^)
# Include <iostream> using namespace std; int main () {int a =-36; int B = 25; // absolute value int tmp = a> 31; /// when a is greater than or equal to 0, tmp is 0. When a is less than 0, tmp is-1 int A = (a ^ tmp)-tmp; cout <A <endl; return 0 ;}
These basic mathematical operations can be implemented by using operators, which are relatively low in time complexity and will be commonly used in the future.