public class Solution { public double pow(double x, int n) { // Recursive problem // If n is odd number: pow(x,n) = x*pow(x,n/2)*pow(x,n/2); // If m is even number: pow(x,n) = pow(x,n/2)*pow(x,n/2); // Finally, if n is negative, we return the reciprocal of pow(x,-n) if (n < 0) return 1.0/power(x, -n); else return power(x, n); } private double power(double x, int n) { // Note: Don't miss this; Otherwise, entering into dead loop. if (n == 0) return 1.0; double v = power(x, n/2); if (n%2 == 0) return v*v; else return x*v*v; } }
Computer Vision & Image Processing & Machine Learning & Pattern Recognition
Thursday, January 8, 2015
LeetCode 50: Pow(x, n)
Implement pow(x, n).
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment