Write procedure is to do two things: algorithm implementation and error handling. Here is some common algorithms and give simple analysis, hoping to have a certain reference value.
1. Judging whether a positive integer is power C implementation: int is2power (unsigned int x) {return (x & (x-1)) == 0;} JAVA implementation: Boolean is2power (int x) {return (x & (x-1)) == 0;} There is not much difference between the two, X & (X-1) is to change the one 1 bit of the rightmost to 0, if X is 2 power, only One bit is 1, the result of the return is 0. Note: x must be a positive integer, 0 nor can it.
2. Judging whether a positive integer is in the form of 2n-1 and the previous problem, there is no difference in the previous problem. Here only gives Java implementation. Boolean is2powerone (int x) {return x & (x 1);}
3. Judging whether a positive integer is in the form of 2J-2K, J> K> = 0.java Implement: Boolean Is2Powerjk (INT X) {RETURN (((x | (x-1)) 1) & x) == 0;} First, we must understand that to meet the form of 2J-2K, the bit of 1 in X must be continuous, that is, the 00 ... 01..10 ... 0, understand this, this is good, X-1 is the 1 bit of the rightmost side and the back, that is, 10 ... 0 becomes 01 ... 1, the high level is unchanged .x | (x-1) makes X's tail 0 becomes 1 The final form is: 000 ... 011..1 This is already in the form of 2N-1, as long as the X & (x 1) formula is available. When j = k 1, it becomes a formula. 1. When k = 0, it becomes equation 2.
4. Ask an absolute value of an integer. Java implementation: int AB {RETURN X - ((x << 1) & (x >> 31));} When N is 0: x << 1 = 0, X >> 31 = 0, the result is 0. When N is positive: x >> 31 is 0, the result is x. When N is negative: x >> 31 is all 1, that is, -1, X- x << 1) is equal to -n but notes: When Integer.min_Value