50. Pow(x, n) (recursion)

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
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]

Solution: recusrion (think about better recursion(memo))

class Solution {
    //when use Math.abs(Integer.MIN_VALUE) overflow
    public double myPow(double x, int n) {
        //make subset (recursive)
        if(n > 0) return powHelper(x, n);
        else if(n<0) return 1/powHelper(x,n);//no need -n 
        else return 1.0;
    }
    double powHelper(double x, int n){
        if(n==0) return 1.0;
        double y = powHelper(x, n/2);
        if(n%2==0) return y*y;
        else return y*y*x;
    }
}

Solution

class Solution {
    //n is even(y*y) and n is odd(y*y*x)
    
    public double myPow(double x, int n) {
        long len = Math.abs((long) n);//point 1: long type
        double res = 1;
        while(len!=0){
            if(len%2!=0) res = res*x;
            x = x*x;//why
            len/=2;
        }
        if(n < 0) return 1/res;
        else return res;
    }
}

Memo + crack the interview

 

posted @ 2018-08-22 10:58  wz30  阅读(155)  评论(0编辑  收藏  举报