Accepted 0ms c++ solution with std::unordered_map to record all the remainders, easy understand.


  • 0

    After the decimal point, we need to record all the remainders and the corresponding position to insert (. When we get a new remainder, we should check whether it is already in the std::unordered_map. If true, it means the fractional part is repeating, so we can break the for loop, then append ) and insert ( to the corresponding position.

    class Solution {
    public:
        std::string fractionToDecimal(long long numerator, long long denominator) {
            if (!numerator)
                return "0";
    		std::string str = numerator < 0 ^ denominator < 0 ? "-" : "";
            numerator = std::abs(numerator);
            denominator = std::abs(denominator);
            str += std::to_string(numerator / denominator);
            long long remainder = numerator % denominator;
            if (!remainder)
                return str;
    		str += '.';
            std::unordered_map<int, int> flag;
    		int pos = str.size();
            while (remainder && flag.find(remainder) == flag.end()) {
                flag[remainder] = pos++;
                str += '0' + remainder * 10 / denominator;
                remainder = remainder * 10 % denominator;
            }
            if (remainder) {
                str += ')';
                str.insert(str.begin() + flag[remainder], '(');
            }
            return str;
        }
    };

Log in to reply
 

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