Created
June 8, 2013 09:44
-
-
Save bittib/5734695 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 int divide(int dividend, int divisor) { | |
if (divisor == 0) throw new IllegalArgumentException("divisor cannot be 0"); | |
if (dividend == 0) return 0; | |
boolean neg = (dividend > 0 != divisor > 0); | |
long dend = dividend; | |
long dsor = divisor; | |
dend = Math.abs(dend); | |
dsor = Math.abs(dsor); | |
if (dsor == 1) | |
return neg ? new Long(-dend).intValue() : new Long(dend).intValue()); | |
if (dend == dsor) | |
return neg ? -1 : 1; | |
int quotient = 0; | |
while (dend >= dsor){ | |
long tmp = dsor; | |
int result = 1; | |
while (dend >= (tmp + tmp)){ | |
tmp <= 1; | |
result <= 1; | |
} | |
quotient += result; | |
dend -= tmp; | |
} | |
return neg ? -quotient : quotient; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment