Magicsheet logo

Compute Decimal Representation

Easy
12.5%
Updated 8/1/2025

Asked by 1 Company

Topics

Compute Decimal Representation

What is this problem about?

The Compute Decimal Representation interview question (often related to fractions) asks you to convert a fraction (numerator/denominator) into its decimal string representation. The tricky part is handling repeating decimals. For example, 1/3 should be represented as "0.(3)", where the repeating part is enclosed in parentheses.

Why is this asked in interviews?

Companies like Meta ask the Math interview pattern to test your ability to handle edge cases and state management. You need to simulate long division manually. The core challenge is detecting when you have entered a cycle (a repeating decimal) and where exactly that cycle started.

Algorithmic pattern used

This problem uses Long Division Simulation and a Hash Table.

  1. Handle the sign (positive/negative) and the integer part (numerator / denominator).
  2. Calculate the remainder (numerator % denominator). If it's 0, you're done.
  3. If not, add a decimal point and start a loop.
  4. In each step, use a Hash Table to store the remainder and its current index in the decimal string.
  5. If you see the same remainder again, it means you've found a cycle! Insert parentheses using the stored index.

Example explanation

Numerator: 1, Denominator: 6

  1. Integer part: 1 / 6 = 0. Remainder = 1.
  2. Decimal: 0.
  3. Remainder 1: Store {1: 2} (index 2 in string).
  4. 1 * 10 = 10. 10 / 6 = 1. New remainder = 4. String: 0.1.
  5. Remainder 4: Store {4: 3}.
  6. 4 * 10 = 40. 40 / 6 = 6. New remainder = 4. String: 0.16.
  7. Remainder 4 is already in the map at index 3.
  8. Cycle detected! Wrap characters from index 3 onwards in parentheses. Result: "0.1(6)".

Common mistakes candidates make

  • Integer Overflow: Using 32-bit integers when numerator * 10 could exceed the limit. Always use 64-bit integers (long).
  • Off-by-one: Placing the opening parenthesis at the wrong position.
  • Negative Numbers: Forgetting to handle negative signs or the absolute value of the inputs correctly.

Interview preparation tip

Always handle the numerator == 0 case separately. Also, be careful with INT_MIN values when taking absolute values in languages like C++.

Similar Questions