g0001_0100.s0029_divide_two_integers.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0029_divide_two_integers;
// #Medium #Top_Interview_Questions #Math #Bit_Manipulation
// #2022_02_18_Time_3_ms_(33.42%)_Space_41_MB_(23.90%)
public class Solution {
public int divide(int dividend, int divisor) {
boolean isNegative = dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0;
long ans = 0;
long divide = Math.abs((long) dividend);
long divisorAbs = Math.abs((long) divisor);
while (divide >= divisorAbs) {
long temp = divisorAbs;
long cnt = 1;
while (divide >= temp) {
divide -= temp;
ans += cnt;
cnt <<= 1;
temp <<= 1;
}
}
if (isNegative) {
ans = -ans;
}
int intMin = -(1 << 31);
int intMax = (1 << 31) - 1;
if (ans < intMin || ans > intMax) {
ans = intMax;
}
return (int) ans;
}
}