【LeetCode】166. Fraction to Recurring Decimal


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.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

 

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

 

這題就是按定義做。

如果不能整除,就不斷進行余數補零除以除數。

維護一個映射表map<long long, int> m, 用來記錄每個除數對應返回值ret中的位置。

(1)當出現重復的除數n時,說明找到了循環體,根據m[n]找到ret中位置,加上相應的'('和')'將循環體括起來即可返回。

(2)當余數r為0時,返回ret。

 

注意點:

1、正負號

2、分子為0

3、可能出現INT_MIN/-1的越界情況,因此第一步現將int轉為long long int

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        // special cases
        if(numerator == 0)
            return "0";
        string ret = "";
        // type conversion in case of INT_MIN
        long long n = numerator;
        long long d = denominator;
        // sign
        int sign = 1;
        bool digit = false;
        if((n<0) ^ (d<0))
            sign = -1;
        n = abs(n);
        d = abs(d);
        unordered_map<long long, int> m;  // numerator --> position
        while(true)
        {
            if(n < d)
            {
                if(digit == false)
                {
                    if(ret == "")
                        ret = "0.";
                    else
                        ret += ".";
                    digit = true;
                }
                n *= 10;
            }
            int r = n - n/d*d;
            if(r == 0)
            {
                ret += to_string(n/d);
                if(sign == -1)
                    ret = "-" + ret;
                return ret;
            }
            else
            {
                if(digit == true)
                {// check recurring
                    if(m.find(n) == m.end())
                    {
                        ret += to_string(n/d);
                        m[n] = ret.size()-1;
                    }
                    else
                    {
                        int pos = m[n];
                        ret = ret.substr(0, pos) + "(" + ret.substr(pos) + ")";
                        if(sign == -1)
                            ret = "-" + ret;
                        return ret;
                    }
                }
                else
                {
                    ret += to_string(n/d);;
                }
                n = r;
            }
        }
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM