leetcode 日经贴,Cpp code -Fraction to Recurring Decimal

来源:互联网 发布:2017十月经济数据公布 编辑:程序博客网 时间:2024/06/07 07:21

Fraction to Recurring Decimal

class Solution {public:    string itostring(long long n) {        string s;        if (!n) return "0";        while (n) {            s = char(n%10 + '0') + s;            n /= 10;        }        return s;    }    string fractionToDecimal(int numerator, int denominator) {        long long a = numerator, b = denominator;        if(b == 0) return "error";        bool neg = (a < 0 && b > 0) || (a > 0 && b < 0);        string ans = neg? "-":"";        if (a < 0) a = -a;        if (b < 0) b = -b;        ans += itostring(a / b);        a %= b;        if (a == 0)            return ans;        vector<int> decimals;        map<int, int> mp;        ans += ".";        while (a) {            if (mp.find(a) != mp.end())                break;            mp[a] = decimals.size();            a *= 10;            decimals.push_back(a / b);            a %= b;        }        for (int i = 0; i < decimals.size(); ++i) {            if (a && mp[a] == i) {                ans += '(';            }            ans += char('0' + decimals[i]);        }        if (a) {            ans += ')';        }        return ans;    }};


0 0