LeetCode – Refresh – Fraction to Recurring Decimal

本文详细阐述了将整数转换为小数的C++算法过程,包括处理特殊情况、使用long long类型避免溢出以及利用哈希表优化循环冗余问题。

Notes:

1. When numerator is 0, return "0". Check this corner case, because 0 / -5 will return -0.

2. Use long long int for divd and divs, mainly for divs. Because when divs = INT_MIN, fabs(divs) is large.

3. Do not forget to rest *= 10 to get the next level.

 

 1 class Solution {
 2 public:
 3     string fractionToDecimal(int numerator, int denominator) {
 4         if (numerator == 0) return "0";
 5         string result;
 6         if (numerator < 0 ^ denominator < 0) result = "-";
 7         long long int divd = fabs(numerator), divs = fabs(denominator), rest = divd % divs;
 8         result += to_string(divd / divs);
 9         if (rest == 0) {
10             return result;
11         }
12         result += '.';
13         unordered_map<int, int> mapping;
14         while (rest > 0) {
15             if (mapping.find(rest) != mapping.end()) {
16                 result.insert(mapping[rest], "(");
17                 result += ')';
18                 return result;
19             }
20             mapping[rest] = result.size();
21             rest *= 10;
22             result += to_string(rest/divs);
23             rest %= divs;
24         }
25         return result;
26     }
27 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4352201.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值