leetcode 166. Fraction to Recurring Decimal

本文介绍了一种算法,用于将任意两个整数表示的分数转换成字符串格式,特别地,如果分数部分是无限循环的,算法会自动识别并使用括号标记循环部分。文章详细解释了算法的实现思路,包括处理零分子、循环小数、溢出风险和正负号等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

给出一个分子,一个分母,返回String型的result,而且当是无限循环小数的时候,要把循环的部分用括号括起来

思路:
(1) 分子=0时返回"0",被除数不能为0,当被除数==0时,返回“0”

(2) 循环小数部分要用括号括起来,因此需要记录循环出现的位置,用HashMap

(3) 防止溢出,将除数和被除数转为long

(4) 当除数和被除数有一个是负数时,开头是负号,后面用绝对值运算

结果是String,先判断正负号,然后将整数部分加入,如果余数是0,则直接返回
如果余数>0, 加上小数点, 在HashMap中记录下余数的位置(结果String的最后)
当计算出的余数存在于HashMap中时, 证明有循环小数,这时在保存的位置处+“(",在结尾处+")"
否则将商加入结果String,计算下一步的余数,直到余数为0

//1ms..
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0 || denominator == 0) {
            return "0";
        }
        
        StringBuilder result = new StringBuilder();
        
        if ((numerator < 0 && denominator > 0) || 
            (numerator > 0 && denominator < 0)) {
            result.append("-");
        }
        
        long divisor = Math.abs((long) numerator);
        long divided = Math.abs((long) denominator);
        
        long remainder = divisor % divided;
        result.append(divisor / divided);
        
        if (remainder == 0) {            
            return result.toString();
        }
        
        result.append(".");
        
        HashMap<Long, Integer> pos = new HashMap<>();
        
        
        while (remainder != 0) {
            if (pos.containsKey(remainder)) {
                result.insert(pos.get(remainder), "(");
                result.append(")");
                break;
            } else {
                pos.put(remainder, result.length());
                result.append(remainder * 10 / divided);
                remainder *= 10;
                remainder %= divided;
            }
            
        }
        
        return result.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值