Java LeetCode除以两个整数-重复指数搜索负数解
我很难理解leetcode中下面的解决方案。为什么int powerOfTwo=-1用-1初始化,因为我们已经处理了divide(int_MIN,-1)的情况 : 添加问题陈述- 给定两个被除数和除数的整数,不使用乘法、除法和mod运算符对两个整数进行除法 返回除数除以除数后的商 整数除法应该向零截断,这意味着丢失其小数部分。例如,truncate(8.345)=8,truncate(-2.7335)=-2 注: 假设我们处理的环境只能存储32位有符号整数范围内的整数:[−2^31, 2^31 − 1]. 对于这个问题,假设函数返回2^31− 1当除法结果溢出时 例1: 输入:除数=10,除数=3 产出:3 说明:10/3=截断(3.33333..)=3Java LeetCode除以两个整数-重复指数搜索负数解,java,algorithm,bit-manipulation,Java,Algorithm,Bit Manipulation,我很难理解leetcode中下面的解决方案。为什么int powerOfTwo=-1用-1初始化,因为我们已经处理了divide(int_MIN,-1)的情况 : 添加问题陈述- 给定两个被除数和除数的整数,不使用乘法、除法和mod运算符对两个整数进行除法 返回除数除以除数后的商 整数除法应该向零截断,这意味着丢失其小数部分。例如,truncate(8.345)=8,truncate(-2.7335)=-2 注: 假设我们处理的环境只能存储32位有符号整数范围内的整数:[−2^31, 2^31
还请解释代码所针对的问题。您的链接只适用于leetcode的高级用户。@ManuelRenePaulsToews当然可以。在原始帖子中添加。谢谢,请解释一下代码所针对的问题。您的链接只适用于leetcode的高级用户。@ManuelRenePaulsToews当然可以。在原始帖子中添加。谢谢
private static int HALF_INT_MIN = -1073741824;
public int divide(int dividend, int divisor) {
// Special case: overflow.
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
/* We need to convert both numbers to negatives.
* Also, we count the number of negatives signs. */
int negatives = 2;
if (dividend > 0) {
negatives--;
dividend = -dividend;
}
if (divisor > 0) {
negatives--;
divisor = -divisor;
}
int quotient = 0;
/* Once the divisor is bigger than the current dividend,
* we can't fit any more copies of the divisor into it. */
while (divisor >= dividend) {
/* We know it'll fit at least once as divivend >= divisor.
* Note: We use a negative powerOfTwo as it's possible we might have
* the case divide(INT_MIN, -1). */
int powerOfTwo = -1;
int value = divisor;
/* Check if double the current value is too big. If not, continue doubling.
* If it is too big, stop doubling and continue with the next step */
while (value >= HALF_INT_MIN && value + value >= dividend) {
value += value;
powerOfTwo += powerOfTwo;
}
// We have been able to subtract divisor another powerOfTwo times.
quotient += powerOfTwo;
// Remove value so far so that we can continue the process with remainder.
dividend -= value;
}
/* If there was originally one negative sign, then
* the quotient remains negative. Otherwise, switch
* it to positive. */
if (negatives != 1) {
return -quotient;
}
return quotient;
}