Why does my code get TLE when it gives correct results on my own computer?


  • 0
    L

    My code gets stuck at the test case (INT_MAX, 1). It always gives me TLE. However, it runs correctly on my own computer. I've successfully run many test cases including INT_MIN and INT_MAX on my own computer.

    Also, I think The method I'm using is the same as many other accepted codes posted online.

    Firstly, I get the absolute value of divisor, named as pdivisor, and dividend, named as pdividend using long type to avoid overflow.

    Then, I keep left shifting pdivisor until it is the biggest smaller value than pdividend. I subtract this value from pdividend and again keep left shifting the original pdivisor to find another biggest smaller value than the remainder of pdividend.

    Keep doing this until the remainder is smaller than pdivisor.

    I am wondering why it will get TLE in OJ. Can anyone help me? Thank you very much!

    int divide(int dividend, int divisor) {
        int res=0;
        int sign=(dividend>0 && divisor>0)||(dividend<0 && divisor<0)?1:-1;
        long pdividend=abs((long)dividend);
        long pdivisor=abs((long)divisor);
    
        long remainder=pdividend;
        while(remainder>=pdivisor)
        {
            int moves=-1;
            long tmp=pdivisor;
            while(tmp <= remainder)
            {
                tmp = tmp<<1;
                moves ++;
            }
            if(moves >= 0)
            {
                res += 1<<moves;
                remainder -= (tmp>>1);
            }
        }
    
        return sign>0?res:-res;;
    }

Log in to reply
 

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