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.
思路:以2/7为例:
class Solution {
public:
string to_string(long x){
std::string number;
std::stringstream strstream;
strstream << x;
strstream >> number;
return number;
}
string fractionToDecimal(int num, int den) {//虽然声明为int,但测试的时候,会用大数
if(num==0){
return "0";
}
string sign="";//结果的符号
if(((num>>31)^(den>>31))!=0){//异号
sign="-";
}
long long numerator=abs((long long)num);//先转成long long,再用abs
long long denominator=abs((long long)den);
if(numerator%denominator==0){//能够整除
return sign+to_string((numerator/denominator));
}
long n=numerator/denominator;//整数部分
numerator=numerator%denominator;//分子
map<int,int> m;
long i=0;
string s="";
bool flag=false;
while(m.find(numerator)==m.end()){
m[numerator]=i;
numerator*=10;
i++;
if(numerator==0){//能够除尽
flag=true;
break;
}
if(numerator<denominator){//不够除,补0
s+="0";
}else{
int l=numerator/denominator;
s+=to_string(l);
numerator%=denominator;
}
}
if(flag){
return sign+to_string(n)+"."+s;
}
int index=m.find(numerator)->second;
return sign+to_string(n)+("."+s.substr(0,index))+"("+s.substr(index,i-index)+")";
}
};
原文地址:http://blog.csdn.net/u010786672/article/details/45565345