0

This question has been answered here.

My query is, following approach-1 works, however the variation of it, that is approach-2 does not, rather it gives time limit exceeded. I can not find out why. I used interviewbit portal to solve this question, and here it is in leetcode.

The issue is

for(; i<32 && ((B<<i)-A <=0); i++) {
}

works, but

for(; i<32 && (B<<i)<=A; i++) {
}

does not work, rather gives Time Limit Exceeds issue.

Approach-1

public class Solution {
    public int divide(int A, int B) {

        //Base Cases
        if (B == 1) {
            return A;
        }
        if (A == Integer.MIN_VALUE && B == -1) {
            return Integer.MAX_VALUE;
        }

        boolean neg = false;
        if((A<0 && B>0) || (A>0 && B<0)) neg=true;
        A = A==Integer.MIN_VALUE ? Integer.MAX_VALUE : Math.abs(A);
        B = Math.abs(B);
        if(A<B) return 0;

        int res=0;
        while(A>=B) {
            int i=0;

            for(; i<32 && ((B<<i)-A <=0); i++) {
            }

            i--;
            res+=(1<<i);
            A-=(B<<i);
        }
      return neg? res*-1 : res;
    }
}

Approach-2

public class Solution {
    public int divide(int A, int B) {

        //Base Cases
        if (B == 1) {
            return A;
        }
        if (A == Integer.MIN_VALUE && B == -1) {
            return Integer.MAX_VALUE;
        }

        boolean neg = false;
        if((A<0 && B>0) || (A>0 && B<0)) neg=true;
        A = A==Integer.MIN_VALUE ? Integer.MAX_VALUE : Math.abs(A);
        B=Math.abs(B);
        if(A<B) return 0;
        int res=0;

        while(A>=B) {
            int i=0;

            for(; i<32 && (B<<i)<=A; i++) {
            }

            i--;
            res+=(1<<i);
            A-=(B<<i);
        }
      return neg? res*-1 : res;
    }
}
srs
  • 330
  • 1
  • 11
  • Check the differences in parentheses. – greybeard Feb 01 '20 at 09:24
  • (I'd use *terminating* a loop, and reserve *breaking* for using a `break` statement.) – greybeard Feb 01 '20 at 09:28
  • Parenthesis difference does not seem to be the issue, `for(; i<32 && ((B< – srs Feb 01 '20 at 10:27
  • Okay, I got the caveat, It seems for Integer.MAX_VALUE the loop is overflowing – srs Feb 01 '20 at 10:33
  • Though I got the bug, can I someone explain in details why the loop is going infinite when `A` is `Integer.MAX_VALUE` or `Integer.MIN_VALUE` with approach-2, and how come approach-1 works – srs Feb 01 '20 at 10:38

0 Answers0