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)"
public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        StringBuilder res = new StringBuilder();
        // "+" or "-"
        res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);
        
        // integral part
        res.append(num / den);
        num %= den;
        if (num == 0) {
            return res.toString();
        }
        
        // fractional part
        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;
            System.out.println(num);
            if (map.containsKey(num)) {
                int index = map.get(num);
                res.insert(index, "(");
                res.append(")");
                break;
            }
            else {
                map.put(num, res.length());
            }
        }
        
        return res.toString();
    }
}
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        StringBuilder result = new StringBuilder();
        String sign = (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-";
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);
        result.append(sign);
        result.append(num / den);
        long rem = num % den;
        if (rem == 0)
            return result.toString();
        result.append(".");
        Map<Long, Integer> map = new HashMap(); //store numerator as repetition of same numerator will cause recurring
        while(rem != 0){
            if(!map.containsKey(rem)){
                 map.put(rem, result.length()); //for a given numerator its (num*10)/den starts from this idx
            }else {
                int idx = map.get(rem);
                return result.substring(0, idx)+"("+result.substring(idx)+")";
            }
            rem*= 10;
            result.append(rem/den);
            rem = rem%den;   
     }   
     return result.toString();
       
}

 

posted @ 2020-06-21 08:11  Schwifty  阅读(162)  评论(0编辑  收藏  举报