- 没想到溢出这码事儿。。。纠结了好久。。。abs只能针对int所以得自己做abs。。。
- 需要记录循环开始的位置
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>
using namespace std;
string fractionToDecimal(int numerator, int denominator) {
string res("");
if (denominator == 0) return res;
stringstream ss;
if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0)) {
ss << "-";
}
long numer = numerator < 0 ? ((long)numerator * (-1)) : ((long)numerator);
long denom = denominator < 0 ? (long)denominator * (-1) : (long)denominator;
cout << numer << " " << denom << endl;
long integer_part = numer / denom;
ss << integer_part;
cout << "integer_part : " << integer_part << endl;
long remainder = numer % denom;
cout << "remainder : " << remainder << endl;
if (remainder == 0) {
return ss.str();
} else {
ss << ".";
}
map<long, int> remainder_map;
bool is_recurring = false;
int decimal_index = 0;
stringstream decimal_ss;
while(remainder != 0) {
if (remainder_map.find(remainder) != remainder_map.end()) {
is_recurring = true;
break;
} else {
long tmp_value = (remainder * 10) / denom;
remainder_map[remainder] = decimal_index;
remainder = (remainder * 10) % denom;
decimal_ss << tmp_value;
cout << "tmp_value : " << tmp_value << " ; remainder : " << remainder << endl;
}
++decimal_index;
}
if (is_recurring) {
int pos = remainder_map[remainder];
string decimal_part = decimal_ss.str();
if (pos > 0) ss << decimal_part.substr(0, pos);
ss << "(";
ss << decimal_part.substr(pos, decimal_part.size() - pos);
ss << ")";
} else {
ss << decimal_ss.str();
}
return ss.str();
}
int main()
{
string res = fractionToDecimal(-1, -2147483648);
cout << res << endl;
return 0;
}