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;
}
}