leetcode 166
我的想法很简单, 先存一下符号, 然后从小数第一位开始进行记录, 每次都乘10 相除, 直到遇到重复的, 为了防止溢出用了long long
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (0 == numerator){
return "0";
}
long long num = numerator, den = denominator, tmp;
// map<long long, int> num_map;
set<long long> num_set;
vector<long long> result_int, tmp_list;
string result = "";
bool postive = false;
// int i = 0;
if ((num < 0 and den < 0) or (num > 0 and den > 0)){
postive = true;
}else {
postive = false;
}
if (false == postive){
result.append("-");
}
if (num < 0){
num = -1 * num;
}
if (den < 0){
den = -1 * den;
}
// result_int.push_back(num / den);
result.append(to_string(num / den));
tmp = num % den;
if (0 == tmp){
return result;
}
result.append(".");
while (0 != tmp){
tmp *= 10;
if (num_set.find(tmp) != num_set.end()){
break;
}
num_set.insert(tmp);
result_int.push_back(tmp / den);
tmp_list.push_back(tmp);
tmp = tmp % den;
}
if (0 == tmp){
for (vector<long long>::iterator i = result_int.begin(); i != result_int.end(); i++){
result.append(to_string(*i));
}
}else{
for(int i = 0; i < result_int.size(); i++){
if (tmp == tmp_list[i]){
result.append("(");
}
result.append(to_string(result_int[i]));
}
result.append(")");
}
return result;
}
};