本文共 1756 字,大约阅读时间需要 5 分钟。
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,
public class Solution { public static String fractionToDecimal(int numerator, int denominator) { String res = ""; long a = Math.abs((long) numerator); long b = Math.abs((long) denominator); if ((denominator < 0 && numerator > 0) || (denominator > 0 && numerator < 0)) { res += "-"; } long intPart= a / b; res += intPart; if (a % b == 0) { return res; } res += "."; long remainder = a % b; HashMapmap = new HashMap (); int i = 1; map.put(remainder, 1); Queue queue = new LinkedList (); int begin = -1; while (remainder != 0) { i++; long tmp = remainder * 10 / b; remainder = remainder * 10 % b; if (map.containsKey(remainder)) { begin = map.get(remainder); queue.offer(tmp); break; } else { map.put(remainder, i); queue.offer(tmp); } } if (remainder == 0) { while (!queue.isEmpty()) { res += queue.poll(); } } else { int j = 1; while (!queue.isEmpty()) { long cur = queue.poll(); if (j != begin) { res += cur; } else { res = res + "(" + cur; } j++; } res += ")"; } return res;}}
转载地址:http://qnuni.baihongyu.com/