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)".
Hint:
1.No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
2.Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
3.Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
先将答案整数部分算出来,如果能整除就返回答案,不能的话计算小数部分。每次用余数乘10除以分母然后保存到表示小数部分的字符串中,然后更新余数。如果余数出现过表示小数要开始循环了,就退出循环。将各位的余数与最后的余数比较,相等的代表循环部分开始的位置,再次处插入“(”,最后在最后插入“)”。
代码:(写的不够简洁)
class Solution {
public:
string fractionToDecimal(long long numerator, long long denominator)
{
string ret;
if(numerator==0) return "0";
if(numerator<0^denominator<0) ret+='-';
if(numerator<0)numerator=~numerator+1;
if(denominator<0) denominator=~denominator+1;
long long x=numerator/denominator;
ret+=to_string(x);
if(numerator%denominator==0) return ret;
ret+='.';
long long yushu=numerator%denominator;
set<long long>s;
vector<long long>y;
y.push_back(yushu);
string den;
while(yushu!=0)
{
if(s.count(yushu)) break;
s.insert(yushu);
den+=to_string(yushu*10/denominator);
yushu=yushu*10%denominator;
y.push_back(yushu);
}
if(yushu==0) ret+=den;
else
{
int i=0;
for(i=0;i<den.size();i++)
{
if(y[i]==yushu) break;
ret+=den[i];
}
ret+='('+den.substr(i,den.size()-i)+')';
}
return ret;
}
};
讨论上写的比较简洁的:
class Solution {
public:
string fractionToDecimal(int64_t n, int64_t d) {
// zero numerator
if (n == 0) return "0";
string res;
// determine the sign
if (n < 0 ^ d < 0) res += '-';
// remove sign of operands
n = abs(n), d = abs(d);
// append integral part
res += to_string(n / d);
// in case no fractional part
if (n % d == 0) return res;
res += '.';
unordered_map<int, int> map;
// simulate the division process
for (int64_t r = n % d; r; r %= d) {
// meet a known remainder
// so we reach the end of the repeating part
if (map.count(r) > 0) {
res.insert(map[r], 1, '(');
res += ')';
break;
}
// the remainder is first seen
// remember the current position for it
map[r] = res.size();
r *= 10;
// append the quotient digit
res += to_string(r / d);
}
return res;
}
};