题目描述:
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.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
long long num=abs((long long)numerator);
long long den=abs((long long)denominator);
long long a=num/den;
long long b=num%den;
string result;
if((numerator>0&&denominator<0)||(numerator<0&&denominator>0)) result+="-";
result+=to_string(a);
if(b==0) return result;
else result+=".";
//用哈希表记录每次余数对应的字符串下标
unordered_map<long long, int> hash;
while(b!=0)//当余数为0,说明除尽,为有限小数
{
if(hash.count(b)>0)
{ //如果余数重复出现说明是无限循环小数,根据记录的字符串下标插入括号
result.insert(hash[b],"(");
result+=")";
return result;
}
else
{
hash[b]=result.size();
b*=10;
result+=to_string(b/den);
b%=den;
}
}
return result;
}
};