Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
- Given numerator = 1, denominator = 2, return "0.5".
- Given numerator = 2, denominator = 1, return "2".
- Given numerator = 2, denominator = 3, return "0.(6)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
题目意思是用一个string来保证除法的结果,如果碰见循环体,将循环的部分用括号括起来。
看了下别人做的,主要是用哈希表来记录余数,如果余数相同的话,则表示是循环了,然后加入括号就可以了。
代码里还是有很些有技巧的地方。
class Solution {
public:
//主要用哈希表map<int,int>第一个数是余数,第二个数是位置,如果余数相同,表示会循环。
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
string res;
if (numerator < 0 ^ denominator < 0) res.push_back('-');
long long int n = numerator, d = denominator;
n = abs(n);
d = abs(d);//处理负数
res = res + to_string(n / d);
long long int r = n%d;
if (r == 0) return res;
res.push_back('.');
map<int, int>Hash;
while (r)
{
if (Hash.find(r) != Hash.end())//找到循环则插入括号
{
res.insert(Hash[r], 1, '(');
res.push_back(')');
break;
}
Hash[r] = res.size();//余数对于与res中的哪个位置
r = r * 10;
res += to_string(r / d);
r = r%d;
}
return res;
}
};