2015年9月17日星期四

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)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (denominator == 0) return "NaN";
        if (numerator == 0) return "0";
        StringBuilder sb = new StringBuilder();
        long n = numerator;
        long d = denominator;
        if (n > 0 != d > 0) {
            sb.append('-');
        }
        n = Math.abs(n);
        d = Math.abs(d);
        long val = n / d;
        sb.append(val);
        long m = n % d;
        if (m == 0) {
            return sb.toString();
        }
        sb.append(".");
        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        while (true) {
            if (map.containsKey(m)) {
                int idx = map.get(m);
                sb.insert(idx, "(");
                sb.append(")");
                break;
            }
            map.put(m, sb.length());
            m *= 10;
            sb.append(m / d);
            m = m % d;
            if (m == 0) break;
        }
        return sb.toString();
    }
}

没有评论:

发表评论