題目描述
Implement pow(x, n), which calculates x raised to the power n (xn).
實(shí)現(xiàn)x的n次方操作。
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
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [?231, 231 ? 1]
思路分析
這個(gè)題很簡(jiǎn)單,最簡(jiǎn)單的方法是遍歷,result*=x;,
- 但是這樣的話復(fù)雜度是O(n)。還可以靈活利用已有的結(jié)果來(lái)降低復(fù)雜度,通過(guò)遞歸,以210為例,可以將210遞歸為25 * 25,依次向下求解。
- 另一方面注意到n的范圍是全部int的范圍,而int的范圍是不對(duì)稱的([?231, 231 ? 1]),因此需要注意負(fù)數(shù)處理時(shí)不能直接將n取-n(通過(guò)x-(n+1)*x遞歸,或者對(duì)Integer.MIN_VALUE進(jìn)行特殊判斷)。
- 另外注意在對(duì)奇偶進(jìn)行判斷和除2時(shí)盡量使用位運(yùn)算(
>> << & |),可以更好的利用計(jì)算機(jī)二進(jìn)制的特性提升性能。(《劍指offer》)
代碼實(shí)現(xiàn)
public class Solution {
/**
* 304 / 304 test cases passed.
* Status: Accepted
* Runtime: 22 ms
* @param x
* @param n
* @return
*/
public double myPow(double x, int n) {
if (n < 0) {
return 1 / x * myPow(1 / x, -(n + 1));
}
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
double half = myPow(x, n >> 1);
half *= half;
if ((n & 1) == 1) {
half *= x;
}
return half;
}
}