您的位置:首页 > 其它

[leetcode] Fraction to Recurring Decimal

2017-05-02 20:59 288 查看
没想到溢出这码事儿。。。纠结了好久。。。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 << "-";
}

// 防止溢出 (-2147483648, -1) (-1, -2147483648)
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; // pos
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: