166 Fraction to Recurring Decimal

题目链接:https://leetcode.com/problems/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.

For example,

Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".

解题思路:
这题的考点是模拟除法运算
关键就是处理循环小数部分。。。用hash表记录余数的位置。如果余数重复出现的话,那就是出现了循环小数。代码中使用HashMap来记录余数,以及余数在字符串中的位置。当第二次出现相同的余数时,说明出现了循环。

这题也包含了很多小细节:
1. 除数不为0
2. 除数或被除数有一者为负数时
3. 当 int 无法表示时,换成 long 类型
4. 当整数部分已经除尽没有小数部分时,不再添加小数点

有网友说这题在面google和facebook中遇到过。

代码实现:

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(denominator == 0) // 分母为0
            return null;
        StringBuilder sb = new StringBuilder();
        if(numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0)
            sb.append("-");
        long numerator1 = Math.abs((long)numerator);
        long denominator1 = Math.abs((long)denominator);
        long quotien = numerator1 / denominator1;
        long reminder = numerator1 % denominator1;
        sb.append(quotien);
        if(reminder == 0)
            return sb.toString();
        sb.append(".");
        int i = sb.length();
        HashMap<Long, Integer> map = new HashMap();
        while(reminder != 0) {
            if(map.containsKey(reminder)) {
                int index = map.get(reminder);
                sb.insert(index, "(");
                sb.append(")");
                break;
            }
            map.put(reminder, i);
            sb.append(reminder * 10 / denominator1);
            reminder = reminder * 10 % denominator1;
            i ++;
        }
        return sb.toString();
    }
}
35 / 35 test cases passed.
Status: Accepted
Runtime: 3 ms
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值