166. Fraction to Recurring Decimal

来源:互联网 发布:淘宝创业项目 编辑:程序博客网 时间:2024/05/20 11:32

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


思路: 若出现循环的数字,则其除数应该是一样的,因此可以用一个map来存储当前除数是否出现过以此来判断循环;同时再计算小数除法的时候,将分子乘以10然后求整计算。

public class Solution {    public String fractionToDecimal(int numerator, int denominator) {        if(numerator==0)            return "0";        StringBuilder res=new StringBuilder("");        //处理符号        res.append(((numerator>0)^(denominator>0))?"-":"");        //考虑到转换为正数后,数值越界的情况,故全部转换为long类型        long num=Math.abs((long)numerator);        long den=Math.abs((long)denominator);                res.append(""+num/den);        num%=den;        if(num==0)        return res.toString();        res.append(".");                HashMap<Long,Integer> map=new HashMap<Long,Integer>();        map.put(num,res.length());        while(num!=0){        num*=10;        res.append(num/den);        num%=den;        if(map.containsKey(num)){        int index=map.get(num);        res.insert(index,"(");        res.append(")");        break;        }        map.put(num,res.length());        }                return res.toString();    }}


0 0