0ms,17 lines readable c++ solution


  • 1
    Z
    string fractionToDecimal(int numerator, int denominator) {
            if(!numerator)return "0";
            string ret;
            long long num=llabs(numerator),deno=llabs(denominator);
            if(numerator<0 ^ denominator<0) ret+='-';
            ret+=to_string(num/deno);
            if(!(num=num%deno))return ret;
            unordered_map<int,int> m;
            ret+='.';
            while(!m.count(num)){
                m[num]=ret.size();
                while((num*=10)<deno) ret+='0', m[num]=ret.size();
                ret+='0'+num/deno;
                if(!(num=num%deno))return ret;
            }   
            ret.insert(m[num],1,'(');
            ret.insert(ret.size(),1,')');
            return ret;
        }

Log in to reply
 

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