166. Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:

Input: numerator = 2, denominator = 1
Output: "2"
Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

這道題可以按照正常的除法計算方法來。使用一個哈希表來保存每次得到的余數(shù),如果遇到相同的余數(shù),說明小數(shù)部分開始重復。

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        string res;
        unordered_map<int,int> data;
        if(numerator == 0)
            return "0";
        long numerator_1 = numerator;
        long denominator_1 = denominator;
        //獲取結果的符號
        if((numerator ^ denominator) < 0)
            res.push_back('-');
        numerator_1 = abs(numerator_1);
        denominator_1 = abs(denominator_1);
        long integer = numerator_1 / denominator_1;
        long remainder = numerator_1 % denominator_1;
        res += to_string(integer);
        if(remainder == 0){
            return res;
        }
        res += '.';
        string digit = "";
        int beginId = 0;
        while(remainder != 0 && data.find(remainder) == data.end()){
            data[remainder] = beginId++;
            remainder *= 10;
            long devideRes = remainder / denominator_1;
            remainder = remainder % denominator_1;
            digit += to_string(devideRes);
        }
        if(remainder == 0){
            res += digit;
            return res;
        }
        else{
            int index = data[remainder];
            digit.insert(index, 1, '(');
            digit.push_back(')');
            res += digit;
            return res;
        }
    }
};
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容