美文网首页
Fraction to Recurring Decimal

Fraction to Recurring Decimal

作者: BLUE_fdf9 | 来源:发表于2018-11-11 12:28 被阅读0次

    题目
    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.

    答案

    class Solution {
        public String fractionToDecimal(int n, int d) {
            Map<Long, Integer> map = new HashMap<>();
            if(n == 0) return "0";
            String sign = ((n > 0) ^ (d > 0)) ? "-":"";
            String ans = "";
    
            long numerator = n, denominator = d;
            numerator = Math.abs(numerator);
            denominator = Math.abs(denominator);
    
            // Calculate integer part
            long integer_part = numerator / denominator;
            ans = ans + Long.toString(integer_part);
    
            // Check if fractional part exists
            if(numerator % denominator != 0)
                ans = ans + ".";
            else
                return sign + ans;
    
            // Calculate fractional part
            for(long r = numerator % denominator; r != 0; r = r % denominator) {
                Integer lookup = map.get(r);
                if(lookup != null) {
                    String part1 = ans.substring(0, lookup);
                    String part2 = ans.substring(lookup, ans.length());
                    ans = part1 + "(" + part2 + ")";
                    break;
                }
                map.put(r, ans.length());
                r = r * 10;
                ans = ans + Long.toString(r / denominator);
            }
    
            return sign + ans;
        }
    }
    

    相关文章

      网友评论

          本文标题:Fraction to Recurring Decimal

          本文链接:https://www.haomeiwen.com/subject/tuyxfqtx.html