45 lines
989 B
Java
45 lines
989 B
Java
/*
|
|
* @lc app=leetcode id=29 lang=java
|
|
*
|
|
* [29] Divide Two Integers
|
|
*/
|
|
|
|
// @lc code=start
|
|
class Solution {
|
|
public int divide(int dividend, int divisor) {
|
|
long x = Math.abs((long)dividend),
|
|
y = Math.abs((long)divisor);
|
|
long r = 0;
|
|
while(true) {
|
|
long[] t = floor(x, y);
|
|
if(t[0] == 0) {
|
|
break;
|
|
}
|
|
x -= t[1];
|
|
r += t[0];
|
|
}
|
|
int sign = (dividend>=0?1:-1) * (divisor>=0?1:-1);
|
|
r = r * sign;
|
|
return (int)Math.max(Math.min(r, Integer.MAX_VALUE), Integer.MIN_VALUE);
|
|
|
|
}
|
|
|
|
private long[] floor(long x, long y) {
|
|
if(x <= y) {
|
|
return x == y ? new long[]{1, y}:new long[]{0, 0};
|
|
}
|
|
long s = y;
|
|
long r = 1;
|
|
while(true) {
|
|
if(s + s > x) {
|
|
break;
|
|
}
|
|
s = s + s;
|
|
r = r + r;
|
|
}
|
|
return new long[] {r, s};
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|