Share my code, 0ms C++


  • 0
    F

    Had a lot of 'fun' with all corner test cases.

    string fractionToDecimal(int numerator, int denominator) {
            bool negative = (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0);
            unsigned long long a = (numerator < 0) ? ~((unsigned int)numerator) + 1 : numerator;
            unsigned long long b = (denominator < 0) ? ~((unsigned int)denominator) + 1 : denominator;
            unsigned long long q = a / b;
            unsigned long long r = a - b * q;
            string ans = negative ? "-" : "";
            ans += to_string(q);
            unordered_map<unsigned long long, int> rPosMap;
            if(r != 0) {
                ans += ".";
                string strFrac;
                int pos=0;
                while(r != 0 && rPosMap.count(r) == 0) {
                    rPosMap[r] = pos++;
                    r = r * 10;
                    q = r / b;
                    r = r - b * q;
                    strFrac.push_back('0' + q);
                }
                if(r != 0) {
                    strFrac.insert(rPosMap[r], 1, '(');
                    strFrac += ")";
                }
                ans += strFrac;
            }
            return ans;
        }
    

Log in to reply
 

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