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)".

 

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

注意溢出:特例-2147483648, 1 | -1, -2147483648 | 

  1. string to_string(long long n) {
  2. stringstream ss;
  3. ss<<n;
  4. string result;
  5. ss>>result;
  6. return result;
  7. }
  8. string fractionToDecimal(int numerator, int denominator) {
  9. if(numerator == 0) return "0";
  10. string result;
  11. if(numerator<0 ^ denominator<0) result += '-';
  12. long long n = numerator, d = denominator;
  13. n = abs(n);
  14. d = abs(d);
  15. result += to_string(n/d);
  16. long long r = n%d;
  17. if(r == 0) return result;
  18. else result += '.';
  19. unordered_map<int,int> exist;
  20. while(r!=0) {
  21. if(exist.find(r) != exist.end()) {
  22. result.insert(exist[r],1,'(');
  23. result += ')';
  24. break;
  25. }
  26. exist[r] = result.size();
  27. r *= 10;
  28. result += to_string(r/d);
  29. r = r % d;
  30. }
  31. return result;
  32. }
posted @ 2014-12-29 15:14  purejade  阅读(98)  评论(0编辑  收藏  举报