Skip to main content

Command Palette

Search for a command to run...

mypow log

Published
1 min readView as Markdown
class Solution {
    public double myPow(double baseVal, int expVal) {
        long expLong = expVal; 
        if (expLong < 0) {
            baseVal = 1 / baseVal;
            expLong = -expLong;
        }
        return fastPowCalc(baseVal, expLong);
    }

    private double fastPowCalc(double curBase, long curExp) {
        if (curExp == 0) return 1.0;

        double halfRes = fastPowCalc(curBase, curExp / 2);

        if (curExp % 2 == 0) {
            return halfRes * halfRes;
        } else {
            return halfRes * halfRes * curBase;
        }
    }
}

More from this blog

Amit singh's blog

235 posts