Notes:

1. When numerator is 0, return "0". Check this corner case, because 0 / -5 will return -0.

2. Use long long int for divd and divs, mainly for divs. Because when divs = INT_MIN, fabs(divs) is large.

3. Do not forget to rest *= 10 to get the next level.

 

 1 class Solution {
 2 public:
 3     string fractionToDecimal(int numerator, int denominator) {
 4         if (numerator == 0) return "0";
 5         string result;
 6         if (numerator < 0 ^ denominator < 0) result = "-";
 7         long long int divd = fabs(numerator), divs = fabs(denominator), rest = divd % divs;
 8         result += to_string(divd / divs);
 9         if (rest == 0) {
10             return result;
11         }
12         result += '.';
13         unordered_map<int, int> mapping;
14         while (rest > 0) {
15             if (mapping.find(rest) != mapping.end()) {
16                 result.insert(mapping[rest], "(");
17                 result += ')';
18                 return result;
19             }
20             mapping[rest] = result.size();
21             rest *= 10;
22             result += to_string(rest/divs);
23             rest %= divs;
24         }
25         return result;
26     }
27 };

 

posted on 2015-03-19 23:09  keepshuatishuati  阅读(128)  评论(0编辑  收藏  举报