[leetcode]pow(x,n)

题目描述

mplement pow(x, n).

代码

  • 递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class {
public double myPow(double x, int n) {
if(n == 0)
return 1;
if(n < 0){
n = -n;
x = 1 / x;

//如果不知道溢出后刚好n没变,就用if else
if(n == Integer.MIN_VALUE){
n = Integer.MAX_VALUE;
x = x * x;
}
}

return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}
}
  • 迭代
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution{
public double myPow(double x, int n){
if(n == 0)
return 1;
// if(n < 0){
// if(n == Integer.MIN_VALUE){
// x = 1 / x;
// x = x * x;
// n = Integer.MAX_VALUE;
// }else{
// n = -n;
// x = 1/x;
// }
// }

if(n < 0){
n = -n;
x = 1 / x;

//如果不知道溢出后刚好n没变,就用if else
if(n == Integer.MIN_VALUE){
n = Integer.MAX_VALUE;
x = x * x;
}
}
double ans = 1;
while(n > 0){
if((n & 1) == 1) ans *= x;
x *= x;
n >>= 1;
}

return ans;
}
}