題目:
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [?231, 231 ? 1]
思路:
這道題可以采用二分法來做骂铁。首先觀察n絮吵。
- 如果n%2為0祈纯,返回x/2 * x/2券册。
- 如果n%2為1改化,返回x/2 * x/2 * x蒂阱。
- 如果n為0共屈,則返回1狭瞎。因?yàn)槿魏螖?shù)除了0之外的0次方全為1.
舉例:
57按照以上原則分解
53 * 53 * 5
51 * 51 * 5 * 51 * 51 * 5 *5
50 * 50 * 5 * 50 * 50 * 5 * 5 * 50 * 50 * 5 * 50 * 50 * 5 * 5 * 5 = 57
注意:
如果n為負(fù)數(shù)柬采,首先按照n的絕對(duì)值計(jì)算xn再用1除以xn欢唾,即最終結(jié)果。
代碼:
/**
* Calculating pow(x, n).
* @param x
* @param n
* @return
*/
public double myPow(double x, int n) {
if(x == 0){
return 0.0;
}
if(n > 0){
return Pow(x, n);
}else{
return 1 / Pow(x, -n);
}
}
private double Pow(double x, int n){
if(n == 0)
return 1;
double mid = Pow(x, n/2);
if(n%2 == 0){
return mid * mid;
}else{
return mid * mid * x;
}
}