Problem

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

Note

逻辑性很强的题目
如果不转换为long去计算:

Input:
-1
-2147483648
Output:
"0.0000000000000000000000000000001"
Expected:
"0.0000000004656612873077392578125"

Solution

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        StringBuilder sb = new StringBuilder();
        //get sign
        String sign = numerator < 0 == denominator < 0 || numerator == 0 ? "" : "-";
        //get integer part
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);
        sb.append(sign).append(num/den);
        
        //if remainder is 0
        long rmd = num%den;
        if (rmd == 0) return sb.toString();
        
        //if remainder not 0,
        //get decimal parts
        sb.append(".");
        //use map to record repeating fractional part
        //update map, remainder and res string until found repeating part
        Map<Long, Integer> map = new HashMap<>();
        while (!map.containsKey(rmd)) {
            map.put(rmd, sb.length());
            sb.append(10*rmd/den);
            rmd = 10*rmd%den;
        }
        
        //deal with repeating part
        int index = map.get(rmd);
        sb.insert(index, "(");
        sb.append(")");
        
        //return res and exclude (0) case
        return sb.toString().replace("(0)", "");
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论