Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses.

Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses.
def frac(n, d):
    q, r = divmod(n, d); s = str(q)
    if r == 0: return s
    s += "."; seen = {}; digits = []
    while r and r not in seen:
        seen[r] = len(digits); r *= 10
        digits.append(str(r // d)); r %= d
    if r:
        i = seen[r]; return s + "".join(digits[:i]) + "(" + "".join(digits[i:]) + ")"
    return s + "".join(digits)
print(frac(5, 74), frac(7, 12))
What is printed?
  1. A. 0.(067) 0.58(3)
  2. B. 0.0(675) 0.(583)
  3. C. 0.0(675) 0.58(3)
  4. D. 0.06(756) 0.5(83)

Correct answer: C. 0.0(675) 0.58(3)

The cycle starts at the digit produced from the first remainder that recurs. 5/74 = 0.0675675…: remainders go 50, 56, 42, 50, so the cycle 675 begins after the first 0. 7/12 = 0.58333…: remainder 4 repeats, so only the 3 is in the cycle.

More Coding Interview Problems questions

Exams that ask this topic