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.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
题意
不使用mod或除法来实现除法运算
题解
一开始使用暴力,非常慢,然后用了二分,快了
1 class Solution { 2 public: 3 int divide(long long dividend, long long divisor) { 4 long long s = 0, e = (long long)INT_MAX+1; 5 long long res = dividend ^ divisor; 6 if (dividend < 0) 7 dividend = -dividend; 8 if (divisor < 0) 9 divisor = -divisor; 10 while (s+1<e) { 11 long long mid = (s + e) / 2; 12 if (mid*divisor <= dividend) 13 s = mid; 14 else 15 e = mid-1; 16 } 17 if (e*divisor <= dividend)s = e; 18 if (res < 0)s = -s; 19 if (s > INT_MAX)s = INT_MAX; 20 if (s < INT_MIN)s = INT_MIN; 21 return s; 22 } 23 };