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)".
leetcode 提供的solution说明:(这个题其实很不好做)
0.16 6 ) 1.00 0 1 0 <-- Remainder=1, mark 1 as seen at position=0. - 6 40 <-- Remainder=4, mark 4 as seen at position=1. - 36 4 <-- Remainder=4 was seen before at position=1, so the fractional part which is 16 starts repeating at position=1 => 1(6).
The key insight here is to notice that once the remainder starts repeating, so does the divided result.
You will need a hash table that maps from the remainder to its position of the fractional part. Once you found a repeating remainder, you may enclose the reoccurring fractional part with parentheses by consulting the position from the table.
The remainder could be zero while doing the division. That means there is no repeating fractional part and you should stop right away.
Just like the question Divide Two Integers, be wary of edge case such as negative fractions and nasty extreme case such as -2147483648 / -1
.
代码如下:(注意要把int变为long long, 否则在处理INT的极限值去相反数时会超出int范围,因为int两边不对称。
string fractionToDecimal(int numerator, int denominator) {
string res;
//考虑0
if(denominator==0) return res;
if(numerator==0) return "0";
long long den=denominator;
long long num=numerator;
//考虑负数
if((float)num/den<0) res.push_back('-');
if(num<0) num=-num;
if(den<0) den=-den;
//考虑小数点
long long remainder=num%den;
long long division=num/den;
res+=to_string(division);
if(remainder==0) return res;
res.push_back('.');
//考虑小数点之后的
map<long long,int> check;
for(int pos=res.size();remainder!=0;pos++,remainder%=den)
{
remainder*=10;
division=remainder/den;
if(check.find(remainder)==check.end()){
char tmp=division+'0';
res+=tmp;
check[remainder]=pos;
}else{
res.insert(res.begin()+check[remainder],'(');
res.insert(res.end(),')');
break;
}
}
return res;
}
注意事项:string的应用,es.insert(res.find('1')+check[division]+1,'(');这句话报错invalid conversion from `char' to `const char*'|
这个回头研究下原因。