My C++ solution, use std::unordered_map


  • 0
    C
    /****
     ****author: cxq
     ****weibo: http://weibo.com/chenxq1992
     ****/
    
    
    class Solution {
    public:
        string fractionToDecimal(int numerator, int denominator) {
            if (numerator == 0) return "0";   
            string result;
            long long n = numerator >= 0 ? numerator : -(long long)numerator; 
            long long d = denominator >= 0 ? denominator : -(long long) denominator;
            int sign = (numerator >> 31) ^ (denominator >> 31);
            if (sign) result += "-";
            result += to_string(n/d);         
            n %= d;
            if (n == 0) return result;
            result += ".";
            int i = 1;
            unordered_map<long long, size_t> cache;
            while (n % d != 0) {
                if (cache.find(n) != cache.end()) {
                    result.insert(result.find('.') + cache.find(n)->second, 1, '(');
                    result.push_back(')');
                    return result;
                }
                cache[n] = i; 
                n *= 10;
                result += to_string(n/d);
                n %= d;
                ++i;
            }
            
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.