LeetCode 166 Fraction to Recurring Decimal
概述
https://leetcode.com/problems/fraction-to-recurring-decimal/
模拟除法 + 哈希表查重
实现的时候注意:
- 注意负数的情况;
- 因为我们把负数做了 abs 处理,所以存在溢出的风险(没错,就给你 -2147483648 恶心你);
四连 WARE,绝绝子。
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
bool neg = false;
long nume = numerator;
long deno = denominator;
if (nume * deno < 0) neg = true;
nume = abs(numerator);
deno = abs(denominator);
unordered_map<int, int> m;
string ans;
int i = 0;
bool afterDot = false;
while (true) {
if (afterDot) {
if (m.count(nume)) {
ans.insert(m[nume], "(");
ans += ")";
break;
}
m[nume] = i;
i ++;
}
long a = nume / deno;
ans += to_string(a);
nume -= a * deno;
if (nume == 0) break;
nume *= 10;
if (!afterDot) {
afterDot = true;
ans += ".";
i = ans.size();
}
}
if (neg) return "-" + ans;
return ans;
}
};