50. Pow(x, n)

Implement pow(x, n).

 Notice

You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than1e-3.

Example
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
分析:
如果n是偶数,那么, power (x, n) = power(x,n/2) * power(x, n/2)。
如果n是奇数,那么, power (x, n) = power(x,n/2) * power(x, n/2) * x.
注意:当负数转成正数的时候,有可能会溢出。
 1 class Solution {
 2     public double myPow(double x, int n) {
 3         if (n == 0 || x == 1) return 1;
 4         if (x == 0) return 0;
 5         if(n == Integer.MIN_VALUE){
 6             x = x * x;
 7             n = n / 2;
 8         }
 9         if (n < 0) return 1 / myPow(x, -n);
10         
11         double result = myPow(x, n / 2);
12         if (n % 2 == 0) {
13             return result * result;
14         }
15         return result * result * x;
16     }
17 }

 

 1 class Solution {
 2     public double myPow(double x, int n) {
 3         long N = n; // use long to handle Integer.MIN_VALUE
 4         if (N < 0) {
 5             x = 1 / x;
 6             N = -N;
 7         }
 8         
 9         double result = 1.0;
10         while (N > 0) {
11             if (N % 2 == 1) { // if N is odd
12                 result *= x;
13             }
14             x *= x; // square the base
15             N /= 2; // halve the exponent
16         }
17         return result;
18     }
19 }

 

posted @ 2016-07-13 10:43  北叶青藤  阅读(186)  评论(0)    收藏  举报