leetcode学习笔记166 Fraction to Recurring Decimal

leetcode学习笔记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.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

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

Example 4:

Input: numerator = 4, denominator = 333
Output: “0.(012)”

Example 5:

Input: numerator = 1, denominator = 5
Output: “0.2”

Constraints:

  • − 2 31 < = n u m e r a t o r , d e n o m i n a t o r < = 2 31 − 1 -2^{31} <= numerator, denominator <= 2^{31} - 1 231<=numerator,denominator<=2311
  • denominator != 0

方法1

时间复杂度O(n).
空间复杂度O(1).

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(numerator == 0)
            return "0";
        
        // 用long来避免overflow
        long n = Math.abs((long)numerator), d = Math.abs((long)denominator);
        StringBuilder res = new StringBuilder();
        Map<Long, Integer> map = new HashMap<Long, Integer>();

        // 结果是否是负数
        res.append((numerator > 0) == (denominator > 0) ? "" : "-");        
        // 整数部分
        res.append(n/d);
        // 去掉整数部分
        n %= d;

        if (n != 0){
            // 小数点
            res.append(".");
            do {
                // 分子的值和对应的位置
                map.put(n, res.length());
                // 乘以10之后进行除法, 得到当前位置的值
                n *= 10;
                res.append(n / d);
                n %= d;
            // 分子不为0, 并且分子没有和之前重复的时候,继续上述操作
            } while (n != 0 && !map.containsKey(n));
            
            // 如果跳出循环,但是分子不为0, 那么就是有重复
            if(n != 0)
                res.insert(map.get(n),"(").append(")");
        }
        return res.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值