convert fraction into string and also insert [] for repeating part

后端 未结 3 1267
抹茶落季
抹茶落季 2021-01-25 14:01

An interview question:

Given two int N (numerator) and D (denominator), return the fraction in string. if the fraction is repeating, then display the repeating part in

3条回答
  •  盖世英雄少女心
    2021-01-25 14:25

    I would avoid using a double like the plague. Due to finite precision, it will not give you the correct answer. Stick to integer arithmetic and simulate long division, keeping track of the remainder. After you run out of digits in the numerator (so you are bringing down zeros), also keep a history of remainders and if you see a remainder that is already in the history, that tells you that you have hit a repeating sequence. You can then construct the bracketed output part. (If you hit a zero remainder, of course, that means that the answer is a terminating fraction.)

提交回复
热议问题