I really need your help!!!!


  • 0
    T
    public double myPow(double x, int n) {
        double res=0.0;
        if(n==0)
          return 1.0;
        boolean flag=false;
        if(n<0){
          flag=true;
          n=-n;
        }
        if(n%2==0){
            res=myPow(x,n/2)*myPow(x,n/2);
        }else{
            res=myPow(x,n/2)*myPow(x,n/2)*x;
        }
        
        if(flag==true){
            res=1.0/res;
        }
        return res;
    }
    

    Above is my code, however, I met the problem:Line 10: java.lang.StackOverflowError 8.88023 3
    I tested it on 8.88023 3 and it's working. I want to know the following questions:

    1.StackOverflowError does that means too much space?

    2.my code is not good because I calculate myPow twice instead of creating double half = myPow(x, n/2) and just use it later?

    1. What's the time complexity of my code and the optimized code like others?

    Thank you so much for teaching me and solving the problem for me!
    Thanks


  • 0
    P

    Because: abs(MIN_INT) > MAX_INT, so when you execute n=-n; it may overflowed. U can define another unsigned int to store -n:

    unsigned in m = -n

  • 0
    T

    Good catch!i think i don't need to change negative to positive at first, thanks!


  • 0
    H
    This post is deleted!

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

  • 0
    H

    Don't make twice recursion of myPow(x, t)


  • 0
    4

    it doesn't, it stores answer from one recursion in res


Log in to reply
 

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