166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal

标签(空格分隔): leetcode hashtable medium


题目

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

思路

本题,题目并不是很难,就是需要考虑一些边界条件:

  • 分子为0
  • 是正数还是负数
  • 是否会发生溢出(被-2147483648坑了好久)
  • 如何判断无限循环小数

考虑完了这些情况后,我们只要按照除法法则,先求出整数部分,然后求小数部分,具体代码注释中有写。(这里我们借助hashtable来存储余数从而来判断是否为无限循环小数)


代码

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        //判断是否为0
        if(numerator==0)
            return "0";
        string res;
        //判断符号
        if(numerator<0^denominator<0)
            res+="-";
        //取绝对值
        long n = labs(long(numerator)); long d = labs(long(denominator));
        //添加整数部分
        cout<<n<<endl;
        res+=to_string(n/d);
        //判断余数是否为0
        if(n%d==0)
            return res;
        res+=".";
        unordered_map<long,long> mp;
        //对余数部分进行判断
        for(long reminder = n%d;reminder;reminder %=d)
        {
            if(mp.count(reminder))
            {
                res.insert(mp[reminder],1,'(');
                res+=")";
                return res;
            }
            mp[reminder] = res.size();
            reminder *=10;
            res +=to_string(reminder/d);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Roaring Kitty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值