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

[leetcode]Fraction to Recurring Decimal

时间:2015-01-01 00:02:23      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

各种情况。有恶心的负数最值,用long long来做了。除此之外的情况下面都列出来了。

/*
1, 8 = 0.125
1, 6 = 0.1(6)
-50, 6 = -6.25
0, -3 = 0
-1, -2147483648 = "0.0000000004656612873077392578125"
*/
typedef long long llong;

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        string result;
        llong n = numerator;
        llong d = denominator;
        if(n < 0 ^ d < 0 ) result+=‘-‘; 
        n = abs(n);
        d = abs(d);
        result += to_string(n / d);
        llong r = n % d;
        if (r == 0) {
            return result;
        } else {
            result += ‘.‘;
        }
        unordered_map<int, int> map;
        while (r != 0) {
            if (map.find(r) != map.end()) {
                result.insert(map[r], 1, ‘(‘);
                result += ‘)‘;
                break;
            }
            map[r] = result.size();
            r *= 10;
            result += to_string(r / d);
            r %= d;
        }
        return result;
    }
};

  

[leetcode]Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/lautsie/p/4196775.html

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