Why the below code give me a time exceeding error?


  • 0
    P

    I cant tell why it gives me an error when testing:
    myPow (0.0001, 27XXXX (a big number))

    Any clues? thank you!

    public class Solution {
        public double myPow(double x, int n) {
            if (x==0.0 && n<0){
                return Double.NaN;
            }
            if (x==0.0){
                return 0.0;
            }
            if (n==0){
                return 1.0;
            }
            if (n==1){
                return x;
            }
            if (n<0){
                return 1/myPow(x,-n);
            }
            return (myPow(x,n/2)*myPow(x,n/2)*myPow(x,n%2));
        }
    }

  • 0

    Because it's only O(n) and that's simply very slow.


  • 0
    P

    I thought it is O(log(n))... myPow(x,n/2) cut n in half each time right?


  • 0

    Yes, cuts it in half, but you do it twice, and two halves are one.


Log in to reply
 

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