[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; }
相关文章推荐
- LeetCode - Fraction to Recurring Decimal
- LeetCode Fraction to Recurring Decimal
- [leetCode] Fraction to Recurring Decimal
- [C++]LeetCode: 82 Fraction to Recurring Decimal
- LeetCode(166) Fraction to Recurring Decimal
- Leetcode (没有转换long long类型) Fraction to Recurring Decimal
- LeetCode—*Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- 【leetcode 哈希表】Fraction to Recurring Decimal
- 【LeetCode】Fraction to Recurring Decimal【Solution】
- [leetcode] Fraction to Recurring Decimal
- [leetcode]Fraction to Recurring Decimal
- LeetCode Fraction to Recurring Decimal
- Leetcode-Fraction to Recurring Decimal
- Leetcode#166 Fraction to Recurring Decimal
- leetcode[166] Fraction to Recurring Decimal
- LeetCode:Fraction to Recurring Decimal
- leetcode[166]Fraction to Recurring Decimal
- leetcode:Fraction to Recurring Decimal