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)".

解决思路

关键点:HashMap中存的是除数和除数的位置。

程序

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        long n = Long.valueOf(numerator);
        long d = Long.valueOf(denominator);
        StringBuilder res = new StringBuilder();
        
        // sign
        if ((n > 0 && d < 0) || (n < 0 && d > 0)) {
            res.append("-");
        }
        
        // abs
        n = Math.abs(n);
        d = Math.abs(d);
        
        long r = n / d;
        res.append(r);
        n = (n % d) * 10;
        if (n != 0) {
            res.append("."); // whether has decimal 
        } else {
            return res.toString();
        }
        
        HashMap<Long, Integer> map = new HashMap<>(); // 存的是除数和此时的位置
        while (n != 0) {
            long dit = n / d;
            if (map.containsKey(n)) {
                // cycle
                String s1 = res.toString().substring(0, map.get(n));
                String s2 = res.toString().substring(map.get(n));
                return s1 + "(" + s2 + ")";
            }
            map.put(n, res.length());
            res.append(dit);
            n = (n % d) * 10;
        }
        
        return res.toString();
    }
}
原文地址:https://www.cnblogs.com/harrygogo/p/4717326.html