C++ 0ms 14 lines simple solution with comments


  • 0
    string fractionToDecimal(int numerator, int denominator) {
            if (numerator == 0 || denominator == 0) { return "0"; }
            long numer = abs((long)numerator), deno = abs((long)denominator), n = 10 * (numer % deno);
            
            // after-dot portion
            string b = n == 0 ? "" : ".";                   // don't miss the '.'
            unordered_map<int, int> idx;                    // to record/find repeating pattern
            
            while (n) {
                if (idx.count(n)) {                         // found repeating pattern
                    b = b.substr(0, idx[n]) + '(' + b.substr(idx[n]) + ')';
                    break;
                }
                
                idx[n] = b.length();                        // record string position for n in hash map
                b.push_back('0' + n / deno);                // record current digit
                n = 10 * (n % deno);                        // update n
            }
            
            // before-dot portion + after-dot portion
            return (numerator < 0 ^ denominator < 0 ? "-" : "") + to_string(numer / deno) + b;
    }
    

Log in to reply
 

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