I am getting a time exceeds problem


  • -1
    V
    public class Solution {
        public int divide(int dividend, int divisor) {
            if (divisor == 1) {
                return dividend;
            }
            if (dividend == Integer.MIN_VALUE) {
                if (divisor == -1) {
                    return Integer.MAX_VALUE;
                } else {
                    return ~divide(Integer.MAX_VALUE, divisor) + 1;
                }
            }
            if (divisor == 0) {
                return Integer.MAX_VALUE;
            }
            boolean neg = false;
            if (dividend < 0) {
                dividend = ~dividend + 1;
                neg = !neg;
            }
            if (divisor < 0) {
                divisor = ~divisor + 1;
                neg = !neg;
            }
            if (divisor > dividend) {
                return 0;
            }
            int result = 0;
            while (dividend >= divisor) {
                int temp = divisor;
                int multiplier = 1;
                while(dividend >= temp << 1) {
                    temp = temp << 1; 
                    multiplier = multiplier << 1;
                }
                dividend -= temp;
                result += multiplier;
                //System.out.println(multiplier);
            }
            if (neg) {
                result = ~result + 1;
            }
            return result;
        }
    }
    

    It seems that I used the correct algorithm but when it comes to the case:
    Integer.MAX_VALUE, 2, the time limit exceeds


  • 0

    @vegetableBird New users please read the instructions to format your code properly.


  • 0

    @vegetableBird Using back quotes ``` (left top or your keyboard) instead of singles ''' (right in your right hand)


Log in to reply
 

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