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.

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

由于两个整数相除会出现一串重复出现的数字,例如1/7 = 0.(142857)
如果此时的numerator =1, 把此时的字符串0.长度2插入,如果再出现1,那么表示后面的都是重复,用括号把2之后的都括起来就行。
于是:
1-2,3-3,2-4,6-5,4-6, 然后又变成1

  • 注意:将int都转为long, 不然在取绝对值的时候会出错。
public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(numerator == 0) return "0";
        StringBuilder res = new StringBuilder();
        if((numerator>0) ^ (denominator>0)) res.append("-");
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);
        
        //integer part
        res.append(num/den);
        num %= den;
        if(num == 0) return res.toString();
        
        //fractional part
        res.append(".");
        Map map = new HashMap<>();
        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;
            }
            else{
                map.put(num, res.length());
            }
        }
        return res.toString();
    }
}

你可能感兴趣的:(166. Fraction to Recurring Decimal)