题目描述(Medium)
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
题目链接
https://leetcode.com/problems/divide-two-integers/description/
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
算法分析
最简单的方法是不断减去除数,在此基础上可以做优化,每次把被除数翻倍,从而加速。
提交代码:
class Solution {
public:
int divide(int dividend, int divisor) {
long long a = dividend >= 0 ? dividend : -(long long) dividend;
long long b = divisor >= 0 ? divisor : -(long long) divisor;
long long result = 0;
while (a >= b) {
long long c = b;
for (int i = 0; a >= c; ++i, c <<= 1) {
a -= c;
result += 1 << i;
}
}
return ((dividend ^ divisor) >> 31) ? -result :(result > INT_MAX ? INT_MAX : result);
}
};