https://leetcode.com/problems/divide-two-integers/description/
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
package go.jacob.day730;
public class Demo2 {
public int divide(int dividend, int divisor) {
// 结果的符号
int flag = 1;
if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))
flag = -1;
//把除数和被除数转化为正数进行判断
long ldividend = Math.abs((long) dividend);
long ldivisor = Math.abs((long) divisor);
if (ldividend == 0 || ldividend < ldivisor)
return 0;
if (ldivisor == 0)
return Integer.MAX_VALUE;
long res = solve(ldividend, ldivisor);
int ans;
//如果结果溢出,根据符号输出相应的值
if (res > Integer.MAX_VALUE)
ans = flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
else
ans = (int) (flag * res);
return ans;
}
private long solve(long ldividend, long ldivisor) {
if(ldividend<ldivisor)
return 0;
long res = 1;
long sum = ldivisor;
//为防止进行多次重复的计算,每一次循环除数*2
while (sum + sum <= ldividend) {
sum += sum;
res += res;
}
return res + solve(ldividend - sum, ldivisor);
}
}