Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created September 24, 2025 21:47
Show Gist options
  • Select an option

  • Save Ifihan/fd69498cf01c56559f14812e1cf5e21c to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/fd69498cf01c56559f14812e1cf5e21c to your computer and use it in GitHub Desktop.
Fraction to Recurring Decimal

Question

Approach

  1. Handle sign: If numerator and denominator have different signs, the result should start with -. Work with absolute values afterward.

  2. Integer part: Perform integer division (numerator // denominator) to get the whole number part.

  3. Remainder handling: If the remainder is zero, just return the integer part as the answer.

  4. Fractional part:

    • Start simulating long division: multiply remainder by 10, divide by denominator, append quotient to result.
    • Keep a dictionary mapping each remainder to the index in the result string where this remainder first appeared.
    • If a remainder repeats, it means we’ve entered a repeating cycle. Insert parentheses around the repeating part and stop.
  5. Return assembled string.

Implementation

Complexities

  • Time: $O(k)$, where $k$ is the length of the decimal expansion before repetition
  • Space: $O(k)$ to store remainders in the dictionary
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment