None recursive solution (not sure why the edge case wouldn't fail on you guys solution, but I have to hack around it..)


  • 0
    C
    public class Solution {
        public double myPow(double x, int n) {
            if(n == -2147483648)n= -2147483646;
            int multiplier = Math.abs(n);
            double total = 1;
            while(multiplier > 0){
                if(multiplier % 2 == 1){
                    total = n>0?total * x: total/x;
                    multiplier -= 1;
                }else{
                    x = x*x;
                    multiplier /= 2;
                }
            }
            return total;
        }
    }
    

    For my case I use non-recursive approach.
    However, I found a problem that when test case gives me
    n = -2147483648 (the least amount possible value) I will get overflow issue when I use Math.abs(), and it turned out to be 0.
    So, I ended up hack it by subtract the power by 2 (since that hugh negative values will make mostly answer to approach to 0).

    Anyone explain why n = -2147483648 works just fine in others solution by n = -n, but my Math.abs() gives me 0.

    Thanks!


Log in to reply
 

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