原题地址:
https://oj.leetcode.com/problems/fraction-to-recurring-decimal/
题目内容:
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)".
方法:
要点有几个
0、模拟除法(自己做一遍,就是笔算复杂除法的过程。)
1、记住你产生的新的被除数以及其index,可以就用一个map来记,为了直观些我加了个set。
2、对产生的新被除数进行判断,如果重复了(map中有了),说明是循环小数,结束循环,在index前面加个括号,当然尾巴括号也要补上。
3、小心负数,由于正负不对称,为了方便我引入了long long类型,这样就不用担心溢出和负数了。
全部代码:
class Solution {
public:
string fractionToDecimal(int numerator1, int denominator1) {
bool isNegti = false;
long long numerator = numerator1;
long long denominator = denominator1;
long long interger = numerator / denominator;
if (numerator * denominator < 0) {
isNegti = true;
interger = -interger;
}
numerator = numerator < 0 ? -numerator : numerator;
denominator = denominator < 0 ? -denominator :denominator;
long long next;
if ((next = numerator % denominator) == 0)
return isNegti == true ? "-" + strval(interger) : strval(interger);
string deci = ".";
unordered_set<long long> dict;
unordered_map<long long,long long> start;
unordered_set<long long>::iterator itDict;
unordered_map<long long,long long>::iterator itStart;
char nownum;
int index = 1;
while (next) {
itDict = dict.find(next);
if (itDict != dict.end()) {
itStart = start.find(next);
int len = itStart->second;
deci = deci.substr(0,len) + '(' + deci.substr(len) + ')';
break;
}
dict.insert(next);
start[next] = index ++;
nownum = (next * 10) / denominator + '0';
deci = deci + nownum;
next = (next * 10) % denominator;
}
return isNegti == true ? "-" + strval(interger) + deci : strval(interger) + deci;
}
static string strval(long long num) {
char tmp[20];
char index = 0;
while (num >= 10) {
tmp[index ++] = (char)(num % 10 + '0');
num /= 10;
}
tmp[index] = (char)(num + '0');
string res = "";
for (int i = index; i >= 0; i --) {
res = res + tmp[i];
}
return res;
}
};