Skip to content

Instantly share code, notes, and snippets.

@wayetan
Last active October 18, 2015 06:46
Show Gist options
  • Save wayetan/9440625 to your computer and use it in GitHub Desktop.
Save wayetan/9440625 to your computer and use it in GitHub Desktop.
Divide Two Integers
/**
* 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