Sort notes-bit operations, sort notes-operations
1. Get the maximum value of the int type:
Int getMaxInt () {return (1 <31)-1; // 2147483647. Brackets cannot be omitted due to priority}
2. obtain the maximum value of the long type:
long getMaxLong(){ return ((long)1 << 127) - 1;//9223372036854775807 }
Others are similar.
3. Division 2 Operation:
Int divTwo (int n) {// return n> 1 cannot be used for negative odd values; // divided by 2}
4. m power operation except 2:
Int divTwoPower (int n, int m) {// calculate n/(2 ^ m) return n> m ;}
5. Judge the parity of a number
boolean isOddNumber(int n){ return (n & 1) == 1; }
6. Do not swap two numbers with temporary variables
a ^= b; b ^= a; a ^= b;
7. Take the absolute value
Int abs (int n) {return (n ^ (n> 31)-(n> 31);/* n> 31 get the n symbol, if n is positive, n> 31 is equal to 0. If n is negative, n> 31 is equal to-1. If n is positive, n ^ 0 = 0, the number remains unchanged, if n is a negative number and n ^-1 needs to calculate the complement code of n and-1, and then perform an exclusive or operation, the result n is changed to the absolute value of n minus 1, minus-1 is the absolute value */}
8. Take the maximum value of two numbers
Int max (int a, int B) {return B & (a-B)> 31) | &(~ (A-B)> 31);/* If a> = B, (a-B)> 31 is 0, otherwise it is-1 */}
9. Take the minimum value of two numbers
Int min (int a, int B) {return a & (a-B)> 31) | B &(~ (A-B)> 31);/* If a> = B, (a-B)> 31 is 0, otherwise it is-1 */}
10. Determine if the symbols are the same
Boolean isSameSign (int x, int y) {// if there is 0, return (x ^ y)> = 0; // true indicates that x and y have the same symbol, false indicates that x and y have the opposite symbol. }
11. Calculate the Npower of 2
Int getFactorialofTwo (int n) {// n> 0 return 2 <(n-1); // n of 2}
12. judge whether a number is a power of 2.
Boolean isFactorialofTwo (int n) {return n> 0? (N & (n-1) = 0: false;/* if it is a power of 2, n must be 100... n-1 is 1111 .... therefore, the calculation result is 0 */}
13. Obtain the remainder from the N power of 2
Int quyu (int m, int n) {// n returns m to the power of 2 & (n-1);/* if it is a power of 2, n must be 100... n-1 is 1111 .... therefore, with the operation result, the non-0 bits of m in the n range are retained */}
14. Take the average of two integers
int getAverage(int x, int y){ return (x + y) >> 1; }
15. From the low position to the high position, take n to the m position
int getBit(int n, int m){ return (n >> (m-1)) & 1; }
16. From the low position to the high position, place n at the m position 1
Int setBitToOne (int n, int m) {return n |... 1... 000 n is performing an OR operation with this number */}
17. From the low position to the high position, set the m position of n to 0.
Int setBitToZero (int n, int m) {return n &~ (1 <m-1);/* shift 1 to the left and find the m-bit. After the reverse operation, the value is 111... 0... 1111 n and then perform operations with this number */}