Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路:注意使用long进行计算,防止int溢出,然后再判断溢出时重置。
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor == 0){
return 0;
}
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
long res = 0;
boolean isPositive = ((dividend ^ divisor) >> 31) == 0;
while (a >= b) {
long c = b;
for (long i = 0; a >= c; i++, c <<= 1) {
a -= c;
res += 1 << i;
if ((isPositive && res > Integer.MAX_VALUE) || (!isPositive && -res < Integer.MIN_VALUE)) {
return Integer.MAX_VALUE;
}
}
}
return isPositive ? (int) res : (int) -res;
}
}

本文提供了一种方法,在不使用乘法、除法和取模操作的情况下,实现两个整数的除法运算。通过使用位操作和递归,确保了运算过程中的数值安全,并且在可能发生溢出时返回最大整数值。
2864

被折叠的 条评论
为什么被折叠?



