Skip to content

Link to Question

MEDIUM

Divide Two Integers

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, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2³¹, 2³¹ − 1]. For this problem, if the quotient is strictly greater than 2³¹ − 1, return 2³¹ − 1. If the quotient is strictly less than −2³¹, return −2³¹.

Example

Input:

dividend = 10, divisor = 3

Output:

3

Explanation:
10 divided by 3 is 3.333..., which truncates toward zero to 3.


Constraints

  • −2³¹ ≤ dividend, divisor ≤ 2³¹ − 1
  • divisor ≠ 0

Solution: Bit Manipulation

  • Time Complexity: O(log N), where N is the absolute value of dividend.
  • Space Complexity: O(1)
C++
class Solution {
public:
    int divide(int dividend, int divisor) {
        // dividend = x * divisor + m (find binary value of x)
        long long a = abs((long long)dividend);
        long long b = abs((long long)divisor);
        int sign = (dividend > 0) == (divisor > 0) ? 1 : -1;
        long long res = 0;
        while(a >= b) {
            int bit = 1;
            while(a >= (b<<bit))
                bit++;
            res += ((long long)1<<(bit-1));
            a -= (b<<(bit-1));
        }
        return res*sign < INT_MIN ? INT_MIN : (res*sign > INT_MAX ? INT_MAX : res*sign);
    }
};