Home » Java » [leet code] Pow(

[leet code] Pow(



Question:, Implement, pow (x, n).




second times to do this problem, still on the 2 to the base of the way to solve problems strange. Intuitive practice, timeout. So can only consider numerical calculation two advanced solution:


1. dichotomy, O (logn)


2. 2 is the base: the target number is disassembled into a composition based on 2, such as 123 = 2^6+2^5+2^4+2^3+2^1+2^0, O (logn),


for the second solution:


Step1: n is a negative number. You need to count the inverse first and check the cross


Step2: for X is negative, the first to determine the results of symbols, in the absolute value for the convenience of subsequent calculation


Step3: x = = Double.MIN_VALUE special case processing, numerical calculation should pay attention to this special situation to deal with cross-border.

-Double.MIN_VALUE

Step4: here really came to 2 as the base solution. The basic idea is to move to the right of a per n, equivalent to x a time with their multiplication (x * = x e.g. (x) =3, n=8) = (x=9, n=7) = (x=81, n=3) = (x=6561, n=1).


because n is equivalent to every /2, then O is still O (logn)


, public, double, myPow (double, x, int, n) {
If (x = = 0) return 0;
If (n = = 0) return 1;
If (n<0 of result) {/ / case <1
If (x>=1/Double.MAX_VALUE || x < = -1/Double.MAX_VALUE) {
X = 1/x;
}
Else{
Return Double.MAX_VALUE;
}
}
N = Math.abs (n);
Boolean neg = false;
If (x<0 & & n%2! =0) {
Neg = true;
}
Double res = 1;
If (x = = Double.MIN_VALUE) {
N -=1;
Res = x;
}
X = Math.abs (x);
While (n, >0) {
If ((n & 1) = = 0) {
If overflow / / check
If (res>Double.MAX_VALUE/x) {
Return Double.MAX_VALUE;
}
Res = x;
}
X = x;
N = n>>1;
}
If (NEG) return -res;
Return res;
}




Latest