1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
public class FractionToRecurringDecimal { public String fractionToDecimal(int numerator, int denominator) { if (denominator == 0) { return ""; } if (numerator == 0) { return "0"; } StringBuilder sb = new StringBuilder(); if ((numerator < 0) ^ (denominator < 0)) { sb.append("-"); } long n = numerator; long d = denominator; n = Math.abs(n); d = Math.abs(d); sb.append(n / d); long remain = n % d; remain *= 10; if (remain == 0) return sb.toString(); sb.append("."); Map<Long, Integer> map = new HashMap<Long, Integer>(); while (remain != 0) { if (map.containsKey(remain)) { int start = map.get(remain); sb.insert(start, "("); sb.append(")"); break; } map.put(remain, sb.length()); sb.append(remain / d); remain = (remain % d) * 10; } return sb.toString(); } @Test public void test() { String result = fractionToDecimal(-1, -2147483648); System.out.println(result); } }
|