How I get the absolute value of Integer.MIN_VALUE


  • 0
    P

    I can not pass this test. I think it's because I can not get the right absolute value of Integer.MIN_VALUE.
    How do you guys handle this problem?

    Submission Result: Time Limit Exceeded
    Last executed input: -1010369383, -2147483648

    public class Solution {
        public int divide(int dividend, int divisor) {
            if(divisor==0){
                return Integer.MAX_VALUE;
            }
            if(dividend==0){
                return 0;
            }
            if(dividend==Integer.MIN_VALUE&&divisor==-1){
                return Integer.MAX_VALUE;
            }
            boolean positive = true;
            if(dividend < 0){
                positive = !positive;
            }
            if(divisor < 0){
                positive = !positive;
            }
    
            dividend = Math.abs(dividend);
            divisor = Math.abs(divisor);
            int div = divisor;
            int c = 1;
            int res = 0;
            if(dividend<divisor){
                return 0;
            }
            while(dividend>=divisor){
                if(dividend>=div){
                    dividend-=div;
                    res+=c;
                    div<<=1;
                    c<<=1;
                }else{
                    c>>=1;
                    div>>=1;
                }
            }
            if(positive){
                return res;
            }else{
                return -res;
            }
           
        }
    }

  • 0
    C

    use long for calculating:

    long ldividend = dividend;
    ldividend = Math.abs(ldividend);

Log in to reply
 

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