Exponentiation by squaring Java


  • 0
    I
    public class Solution {
    	public double myPow(double x, int n) {
    		return n >= 0 ? pow(x, n, 1.0) : 1 / (x * pow(x, -n-1, 1.0));
    	}
    
    	private double pow(double x, int n, double r) {
    		if (n == 0) return r;
    		return n % 2 == 0 ? pow(x*x, n>>1, r) : pow(x, n-1, r*x);
    	}
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.