2014年5月11日星期日

Binary Solution - Pow(x, n) *

Check edge condition like n < 0, then x = 1/x. Then implement binary solution, by iteration n > 0 case. and take the advantage of n%2 will eventually equal to 1, so the last iteration will definitely hit here. Np as the temporary result for each iteration.

public class Solution {
    public double pow(double x, int n) {
        if(x == 0 || n == 1){
            return x;
        }
        if(n == 0){
            return 1;
        }

        if(n < 0){
            x = 1 / x;
            n = n * (-1);
        }
        double result = 1;
        double np = x;
        while(n > 0){
            if(n % 2 == 1)
                result = result * np;
            np = np * np;
            n = n / 2;
        }
        return result;
    }
}

没有评论: