码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Fraction to Recurring Decimal

时间:2015-03-19 23:44:46      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

LeetCode – Refresh – Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!