166. Fraction to Recurring Decimal

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

  

posted @ 2017-10-24 07:13  Weiyu Wang  阅读(88)  评论(0编辑  收藏  举报