Leetcode 166. Fraction to Recurring Decimal

来源:互联网 发布:移动光纤网络机房在哪 编辑:程序博客网 时间:2024/06/13 20:28
public class Solution {    public String fractionToDecimal(int numerator, int denominator) {        // determin the sign first        // careful of the case n=0, d>0, so return 0 when numerator equals to 0        if (numerator == 0) return "0";        StringBuilder ret = new StringBuilder();        if (numerator>0 ^ denominator>0) ret.append("-");                // calculate the remainder        long n = new Long(numerator);        long d = new Long(denominator);        n = Math.abs(n);        d = Math.abs(d);        ret.append(n / d);        long remainder = n % d;        if (remainder == 0) return ret.toString();                // calculate the decimal part        // need a hashset to save decimal, if meets a duplicate number return (...)        HashMap<Long, Integer> map = new HashMap<Long, Integer>();        ret.append(".");        while (remainder != 0) {            if (map.containsKey(remainder)) {                ret.insert(map.get(remainder), "(");                ret.append(")");                return ret.toString();            }            map.put(remainder, ret.length());            n = remainder * 10;            long quotient = n / d;            remainder = n % d;            ret.append(quotient);        }        return ret.toString();    }}

0 0
原创粉丝点击