Divide Two Numbers Without Division, Multiplication or Modulus
Given two integers, divide the first number by the second number without using division, multiplication, or modulus operations. Return the quotient as a string containing at most two digits after the decimal point.
Method Signature
String divide(int dividend, int divisor)
dividend is the number to be divided.
divisor is the non-zero number by which to divide.
- Return the quotient as a string with at most two digits after the decimal point.
Calculation Rules
- If the quotient contains more than two fractional digits, truncate it toward zero after the second fractional digit.
- Do not round the result.
- The result must be negative exactly when one input is negative and the other is positive.
- A zero dividend must produce
"0".
Output Format
- Return the result as a string.
- Do not include unnecessary trailing zeroes after the decimal point.
- Do not include a decimal point when the quotient has no fractional part.
- Do not return a negative zero such as
"-0" or "-0.00".
Operation Restrictions
- The operators
/, *, and % must not be used anywhere in the solution.
- The restriction applies to every intermediate calculation, including calculating the integer part, remainder, and fractional digits.
- Helper methods must also follow the same restriction.
- Library methods that internally perform division, multiplication, or modulus to calculate the quotient must not be used.
- Floating-point arithmetic must not be used to calculate the result.
- Addition, subtraction, comparisons, loops, bitwise operations, and string operations may be used.
- A solution that produces the correct output while violating any operation restriction is considered invalid.
Constraints
-2,147,483,648 ≤ dividend ≤ 2,147,483,647
-2,147,483,648 ≤ divisor ≤ 2,147,483,647
divisor != 0
- The returned result may represent a value outside the 32-bit signed integer range.
Examples
Example 1
divide(dividend = 22, divisor = 7)
Output: "3.14"
The quotient continues beyond two fractional digits, so it is truncated after 3.14.
Example 2
divide(dividend = -19, divisor = 8)
Output: "-2.37"
The exact quotient is -2.375, which is truncated toward zero to -2.37.
Example 3
divide(dividend = 42, divisor = 6)
Output: "7"
The quotient is a whole number, so no decimal point is included.
Example 4
divide(dividend = 1, divisor = 8)
Output: "0.12"
The exact quotient is 0.125, which is truncated to two fractional digits.
Example 5
divide(dividend = 15, divisor = 10)
Output: "1.5"
The unnecessary trailing zero is omitted from 1.50.