leetcode[166]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.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

题目大意:

给定除数和被除数,返回除数除以被除数的结果。

解法:

先得到整数部分,再模拟除法获取小数部分。使用一个map来存储余数,当余数重复出现的时候说明该结果是一个循环小数。

java:

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(numerator==0) return "0";
        if(numerator==Integer.MAX_VALUE&&denominator==-1) return String.valueOf((double)numerator/(double)denominator);
        long num=(long)numerator;
        long den=(long)denominator;
        boolean positive=true;
        if(num*den<0) positive=false;
        num=Math.abs(num);
        den=Math.abs(den);
        String pre=String.valueOf(num/den);
        if(!positive) pre='-'+pre;
        long remain=num%den;
        if(remain==0) return pre;
        HashMap<Long,Integer>m=new HashMap<Long, Integer>();
        StringBuilder str=new StringBuilder();
        int index=0;
        while(remain!=0&&!m.containsKey(remain)){
            str.append(String.valueOf((remain*10)/den));
            m.put(remain,index++);
            remain=(remain*10)%den;
        }
        if(remain==0) return pre+'.'+str.toString();
        else{
            str.insert((int)m.get(remain),'(');
            str.append(')');
            return pre+'.'+str.toString();
        }
    }
}

  

---恢复内容结束---

posted @ 2019-04-23 21:23  小白兔云  阅读(116)  评论(0编辑  收藏  举报