75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

50. Pow(x, n)

O(N) Time Brute force

Code (TLE)

class Solution {
public:
    double myPow(double x, int n)
    {
        if (n == 0) return 1.0;
        double ans = x;
        // long long tempN = (n > 0) ? n : -n; // DON'T-int overflow
        long long tempN = n;
        if(tempN<) tempN = -tempN; // DO
        bool neg = (n > 0) ? false : true;
        for (int i = 2; i <= tempN; i++) {
            ans *= x;
        }
        if (neg) {
            ans = 1.0 / ans;
        }
        return ans;
    }
};

O(log2_N) optimized

class Solution {
public:
    double myPow(double x, int n)
    {
        double ans = 1.0;
        long long tempN = n;
        if (tempN < 0) tempN = -1 * tempN;
        while (tempN) {
            if (tempN % 2 == 1) { //odd
                ans *= x;
                tempN -= 1;
            } else { // even
                x *= x;
                tempN /= 2;
            }
        }
        if (n < 0) ans = 1.0 / ans;
        return ans;
    }
};

Recursive

Code

class Solution {
public:
    double myPow(double x, int n)
    {
        if (n < 0) return 1 / x * myPow(1 / x, -(n + 1));
        if (n == 0) return 1;
        if (n == 2) return x * x;
        if (n % 2 == 0)
            return myPow(myPow(x, n / 2), 2);
        return x * myPow(myPow(x, n / 2), 2);
    }
};