首页 > 代码库 > [leetcode]Fraction to Recurring Decimal

[leetcode]Fraction to Recurring Decimal

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

/*1, 8 = 0.1251, 6 = 0.1(6)-50, 6 = -6.250, -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