一、题目描述
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:
- No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
- Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
- Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
思路:
1、判断正负数,如果是负数,则加'-' 符号
2、n和d分别取绝对值,消除正负数的影响
3、求小数点前面的数
4、求小数点后面的数
a. 假设当前的数是n 并且n>10
b. 将n/d的值入结果
c. 设置n = (n%d)*10
d. 并将n为key,字符串长度入哈希表;table[n] = 当前的位置(可以是字符串的位置,也可以是小数点后的数字组成的字符串的位置)
e. 循环step a
5、如果n不等于0,说明第四步结束的原因是因为存在循环的数。
a. 在循环数的位置插入'(':该位置等于table[n]
b. 在结尾的位置插入')'
6、返回结果。
c++代码(0ms,83.76%):
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string res;
if(!numerator) return "0";
if(numerator<0 ^ denominator<0)
res += '-';
long num = abs(long(numerator));
long den = abs(long(denominator));
long quotient = num/den;
if(num%den == 0)
return res += to_string(abs(num/den));
res += to_string(quotient);
res += '.';
long rmd = num%den;
unordered_map<long, long> m;
while(rmd){
if(m.find(rmd)!=m.end()){
res.insert(m[rmd], 1, '(');
res+=')';
break;
}
m[rmd] = res.size();
res += to_string(rmd*10/den);
rmd = (rmd*10%den);
}
return res;
}
};