Last active
October 18, 2015 06:46
-
-
Save wayetan/9440625 to your computer and use it in GitHub Desktop.
Divide Two Integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Divide two integers without using multiplication, division and mod operator. | |
*/ | |
public class Solution { | |
public int divide(int dividend, int divisor) { | |
if(dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE; | |
int res = 0; | |
boolean isNeg = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0); | |
// a / b | |
long a = dividend, b = divisor; | |
a = a < 0 ? -a : a; | |
b = b < 0 ? -b : b; | |
while(a >= b) { | |
int multi = 1; | |
long tmp_divisor = b; | |
while(a >= tmp_divisor) { | |
a -= tmp_divisor; | |
res += multi; | |
tmp_divisor += tmp_divisor; | |
multi += multi; | |
} | |
} | |
res = isNeg ? -res : res; | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment