Sitemap
Siddharth

Siddharth

Cool!

Divide two integers

1 min readApr 6, 2026

https://leetcode.com/problems/divide-two-integers/description/

Get Siddharth’s stories in your inbox

Join Medium for free to get updates from this writer.

Divide two integers in leetcode python with some catches.

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.

  • I had to abs value both dividend and divisor at the start, also keep a variable valued at 0.
  • So we had to create a while loop, if divident was greater than = divisor we minus d - dv and add 1 to output.
  • This code checks whether one of the dividend or divisor is negative. If so, it makes the output negative to ensure the correct sign of the division result.
class Solution(object):
def divide(self, dividend, divisor):
d = abs(dividend)
dv = abs(divisor)
output = 0

while d >= dv:
d -= dv
output += 1

if (dividend < 0 and divisor >= 0) or (divisor < 0 and dividend >= 0):
output = -output

return output

--

--