166. Fraction to Recurring Decimal

13 篇文章 0 订阅
3 篇文章 0 订阅

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

Analysis:

本题的思路是模拟除法运算,但是需要记住每次小数运算的结果,一旦出现重复的数字那么它就可能会出现循环小数,使用Map来记录,此时也就可以终止运算。代码如下:

Code:

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        
        StringBuilder sb = new StringBuilder();
        
        int gcd = Gcd(numerator, denominator);
        long nu = Math.abs((long)numerator/gcd);
        long de = Math.abs((long)denominator/gcd);
        Map<Long, Integer> temp = new HashMap<Long, Integer>();
        
        sb.append(String.valueOf(nu/de));
        nu = nu%de;
        if(nu != 0)
            sb.append(".");
        int cnt = sb.length() - 1;
        while(nu != 0) {
            long ans = nu * 10;
            if(!temp.containsKey(nu)) {
                cnt++;
                sb.append(String.valueOf(ans/de));
                temp.put(nu, cnt);
            } else {
                sb.insert(temp.get(nu), "(");
                sb.append(")");
                break;
            }
            nu = ans%de;
        }
        if((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0)) {
            sb.insert(0, "-");
        }
        return sb.toString();
    }
    
    private int Gcd(int a, int b) {
        while(b != 0) {
            int temp = b;
            b = a%b;
            a = temp; 
        }
        return a;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值