Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Divide Two Numbers Without Division

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Divide Two Numbers Without Division. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Hewlett Packard Enterprise Development systems may need arithmetic logic implemented without relying on hardware division or multiplication instructions. Given two integers, compute the quotient without using /, //, or *.

Requirements

Implement divide(a, b) with these rules:

  1. Return the quotient of a divided by b, truncated toward zero.
  2. b is never zero.
  3. Do not use division, floor division, multiplication, exponentiation, or equivalent library operations.
  4. Use addition, subtraction, comparison, and basic control flow. Bit shifts are not required.
  5. Clamp the result to the signed 32-bit range [-2147483648, 2147483647].

The solution should improve on subtracting the divisor one time per quotient unit by repeatedly doubling the largest usable divisor chunk.

Formal Specification

Input: two integers a and b.

Output: one integer representing a / b, truncated toward zero and clamped to the signed 32-bit range.

Constraints

  • -2147483648 <= a, b <= 2147483647
  • b != 0
  • Return truncation toward zero
  • Return values must remain within [-2147483648, 2147483647]
  • Do not use /, //, *, or exponentiation

Function Signature

def divide(a, b):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output