166. 分数到小数
class Solution {
public:
string fractionToDecimal(int n, int d) {
typedef long long LL;
LL x = n, y = d;
if (x % y == 0) return to_string(x / y);
string res;
if ((x < 0) ^ (y < 0)) res += '-';
x = abs(x), y = abs(y);
res += to_string(x / y);
x %= y;
res += '.';
unordered_map<LL, int> hash;
while (x) {
hash[x] = res.size();
x *= 10;
res += to_string(x / y);
x %= y;
if (hash.count(x)) {
res = res.substr(0, hash[x]) + '(' + res.substr(hash[x]) + ')';
break;
}
}
return res;
}
};
这篇博客介绍了一种用C++将分数转换为小数的方法,通过定义一个名为`Solution`的类,实现了`fractionToDecimal`函数。该函数首先检查正负号,然后进行整数部分的转换,接着进行小数部分的处理,利用哈希表避免无限循环,并在遇到重复数字时插入括号。这个解决方案对于理解和实现分数到小数的转换非常有帮助。
340

被折叠的 条评论
为什么被折叠?



