Fraction to Recurring Decimal

描述

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

    分析

这题的难点是如何找到无限循环的那一段。仔细回想一下人脑进行除法的过程,会发现,当一个余数第二次重复出现时,就说明小数点后开始无限循环了。

代码

  1. // Fraction to Recurring Decimal
  2. // Time Complexity: ?, Space Complexity: ?
  3. public class Solution {
  4. public String fractionToDecimal(int numerator, int denominator) {
  5. if (numerator == 0) return "0";
  6. final StringBuilder result = new StringBuilder();
  7. // determine the sign
  8. if ((numerator < 0) ^ (denominator < 0)) result.append('-');
  9. // Integer.MIN_VALUE will overflow, so use long
  10. // Math.abs(MIN_VALUE) will overflow
  11. long n = numerator;
  12. n = Math.abs(n);
  13. long d = denominator;
  14. d = Math.abs(d);
  15. // append integral part
  16. result.append(String.valueOf(n / d));
  17. if (n % d == 0) return result.toString();
  18. result.append('.');
  19. final Map<Long, Integer> map = new HashMap<>();
  20. // simulate the division process
  21. for (long r = n % d; r != 0; r %= d) {
  22. // find a existed remainder, so we reach
  23. // the end of the repeating part
  24. if (map.containsKey(r)) {
  25. result.insert(map.get(r), "(");
  26. result.append(')');
  27. break;
  28. }
  29. map.put(r, result.length());
  30. r *= 10;
  31. result.append(Character.forDigit((int)(r/d), 10));
  32. }
  33. return result.toString();
  34. }
  35. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/number-theory/fraction-to-recurring-decimal.html