Why this code doesn't pass the time limit?


  • 0
    U

    public static int divide(int dividend, int divisor) {
    int answer = 0;
    int new_dividend = dividend;
    while(true){
    new_dividend = Math.abs(dividend) - Math.abs(divisor);
    if(new_dividend>=0){
    answer++;
    }
    else{
    if(dividend > 0 && divisor<0 )
    return 0-answer;
    else{
    return answer;
    }
    }

            }
            
        }

  • 0
    M

    The value of new_dividend never changes. because if it is positive, you increment answer. On the next iteration of the loop you recompute new_dividend using the original dividend and divisor values. Since new_dividend never changes, you have an infinite loop.


Log in to reply
 

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