Monday, 15 August 2016

Pow(X, n)

Implement a function that takes two integers and returns x^n.
Approach : Using divide and conquer to calculate the power. Remember to handle both positive and negative powers. 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
    double myPower(double x, int n){
        if(n == 0){
            return 1;
        }
        double res = myPower(x, n / 2);
        //if n is even, then x ^ n = x ^ n/2 * x ^ n/2
        if(n % 2 == 0){
            return res * res;
        }
        //else x ^ n = x ^ n/2 * x ^ n/2 * x
        else {
            return res * res * x;
        }
    }
    
    double myPow(double x, int n) {
        //if n < 0 return 1 / power(x, -n)
        if(n < 0){
            return 1 / myPower(x, -1 * n);
        }else{
            return myPower(x, n);
        }
    }
};
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts