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)".
此题的思路并不难,但是程序较复杂,各种情况都容易出错
我的代码:当处理1/90时,答案为0.0(11),应该是因子是10的倍数导致的
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string left;
string right;
bool re=false;
if(numerator==0) return left+"0";
if(denominator==0) return left;
unordered_map<int,int> hash;
hash[numerator]=0;
int first=0,last=0;
if(numerator>=denominator)
{
left+=to_string(numerator/denominator);
if(numerator%denominator)
{
fraction(numerator%denominator,denominator,right,numerator,re,hash,last,first);
}
}
else
{
fraction(numerator,denominator,right,numerator,re,hash,last,first);
}
string res;
if(!left.empty()) res+=left;
else res+="0";
if(!right.empty())
{
if(re) {
res.push_back('.');
for(int i=0;i<first;i++)
{
res.push_back(right[i]);
}
res+="("+right.substr(first)+")";
}
else res+="."+right;
}
return res;
}
void fraction(int num,const int& de,string& right,const int& nu,bool& re,unordered_map<int,int>& hash,int& last,int& first){
int zero=0;
while(num<de)
{
zero++;
num*=10;
}
int temp=num/de;
int ba=zero;
while(ba-->1)
{
right+="0";
}
right+=to_string(temp);
last++;
while(zero>nu&&zero%10==0)
{
zero/=10;
}
if(hash.find(num%de)!=hash.end()) {
re=true;
first=hash[num%de];
return ;
}
if(num%de==0) return ;
hash[num%de]=last;
fraction(num%de,de,right,nu,re,hash,last,first);
}
};