304 North Cardinal St.
Dorchester Center, MA 02124

# Divide Two Integers LeetCode Solution

## Problem – Divide Two Integers

Given two integers `dividend` and `divisor`, divide two integers without using multiplication, division, and mod operator.

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`.

Return the quotient after dividing `dividend` by `divisor`.

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

Example 1:

``````Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = 3.33333.. which is truncated to 3.
``````

Example 2:

``````Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = -2.33333.. which is truncated to -2.``````

Constraints:

• `-231 <= dividend, divisor <= 231 - 1`
• `divisor != 0`

### Divide Two Integers LeetCode Solution in C++

``````    int divide(int A, int B) {
if (A == INT_MIN && B == -1) return INT_MAX;
int a = abs(A), b = abs(B), res = 0, x = 0;
while (a - b >= 0) {
for (x = 0; a - (b << x << 1) >= 0; x++);
res += 1 << x;
a -= b << x;
}
return (A > 0) == (B > 0) ? res : -res;
}
``````

### Divide Two Integers LeetCode Solution in Java

``````    public int divide(int A, int B) {
if (A == 1 << 31 && B == -1) return (1 << 31) - 1;
int a = Math.abs(A), b = Math.abs(B), res = 0, x = 0;
while (a - b >= 0) {
for (x = 0; a - (b << x << 1) >= 0; x++);
res += 1 << x;
a -= b << x;
}
return (A > 0) == (B > 0) ? res : -res;
}
``````

### Divide Two Integers LeetCode Solution in Python

``````    def divide(self, A, B):
if (A == -2147483648 and B == -1): return 2147483647
a, b, res = abs(A), abs(B), 0
for x in range(32)[::-1]:
if (a >> x) - b >= 0:
res += 1 << x
a -= b << x
return res if (A > 0) == (B > 0) else -res``````
##### Divide Two Integers LeetCode Solution Review:

In our experience, we suggest you solve this Divide Two Integers LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Divide Two Integers LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Divide Two Integers LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions