10-03每日一题:Leetcode 166. 分数到小数
作者:互联网
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;
}
};
标签:10,hash,string,03,int,res,LL,substr,166 来源: https://blog.csdn.net/MATLAB2020ab/article/details/120591561