Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
string res;
if ((numerator ^ denominator) < 0) { // 异号
res += '-';
}
long a = labs(numerator);
long b = labs(denominator);
// 计算小数点之前的数
if (a < b) {
res += "0.";
} else {
res += to_string(a / b);
if (a % b == 0) return res;
res += '.';
a = a % b;
}
// 计算小数点之后的数
unordered_map<int, int> m; // 每次做除法得到的余数,及其对应的小数位
int cnt = 0;
while (a % b) {
a *= 10;
res += to_string(a / b);
a %= b;
if (m.count(a)) { // 出现相同余数则说明是无限循环小数
// 在小数点位置后添加左括号,并在结果字符串最后添加右括号
int dot_pos = res.find('.') + 1 + m[a];
res.insert(dot_pos, "(");
res += ')';
break;
}
m[a] = ++cnt;
}
return res;
}
};