leetcode/src/s0029_divide_two_integers.cpp

38 lines
1.5 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "s0029_divide_two_integers.hpp"
// 举个例子11 除以 3 。
// 首先11比3大结果至少是1
// 然后我让3翻倍就是6发现11比3翻倍后还要大那么结果就至少是2了那我让这个6再翻倍得1211不比12大吓死我了差点让就让刚才的最小解2也翻倍得到4了。但是我知道最终结果肯定在2和4之间。也就是说2再加上某个数这个数是多少呢我让11减去刚才最后一次的结果6剩下5我们计算5是3的几倍也就是除法递归出现了。
int S0029::div(long a, long b) { // 似乎精髓和难点就在于下面这几句
if (a < b) return 0;
long count = 1;
long tb = b; // 在后面的代码中不更新b
while ((tb + tb) <= a) {
count = count + count; // 最小解翻倍
tb = tb + tb; // 当前测试的值也翻倍
}
return count + div(a - tb, b);
}
int S0029::divide(int dividend, int divisor) {
if (dividend == 0) return 0;
if (divisor == 1) return dividend;
if (divisor == -1) {
if (dividend > INT_MIN)
return -dividend; // 只要不是最小的那个整数,都是直接返回相反数就好啦
return INT_MAX; // 是最小的那个,那就返回最大的整数啦
}
long a = dividend;
long b = divisor;
int sign = 1;
if ((a > 0 && b < 0) || (a < 0 && b > 0)) {
sign = -1;
}
a = a > 0 ? a : -a;
b = b > 0 ? b : -b;
long res = div(a, b);
if (sign > 0) return res > INT_MAX ? INT_MAX : res;
return -res;
}