1. 程式人生 > >【LeetCode】166. 分數到小數 結題報告 (C++)

【LeetCode】166. 分數到小數 結題報告 (C++)

原題地址:https://leetcode-cn.com/problems/fraction-to-recurring-decimal/description/

題目描述:

給定兩個整數,分別表示分數的分子 numerator 和分母 denominator,以字串形式返回小數。

如果小數部分為迴圈小數,則將迴圈的部分括在括號內。

示例 1:

輸入: numerator = 1, denominator = 2
輸出: "0.5"
示例 2:

輸入: numerator = 2, denominator = 1
輸出: "2"
示例 3:

輸入: numerator = 2, denominator = 3
輸出: "0.(6)"

 

解題方案:

將字串轉化為整形進行計算

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        long long t = numerator, d = denominator;
        map<long long, int> A;
        string ans;
        if (t * d < 0) ans = "-";
        t = abs(t), d = abs(d);
        ans += to_string(t / d);
        t %= d;
        if (!t) return ans;
        ans += '.';
        while (t) {
            if (A.count(t)) {
                ans.insert(A[t], "("), ans.push_back(')');
                return ans;
            }
            A[t] = ans.size(), ans += '0' + t * 10 / d;
            t = t * 10 % d;
        }
        return ans;
    }
};