My simple c++ solution


  • 0
    K
    class Solution {
    public:
    string fractionToDecimal(int a, int b) {
        string res="";
        if(b==a)return {"1"};
        int sign =(a>=0 ^ b >=0)?-1 : 1;
        if(sign == -1 && a!=0)res+="-";
        long A=labs(long(a));
        long B=labs(long(b));
        
        long diff=0;
        bool pointer=false;
        unordered_map<long, int>map;
        while(1){
            res+= to_string(A/B);
            diff=A%B;
            if(diff==0)return res;
            if(diff < B && !pointer){
                    res+=".";
                    pointer=true;
            }
            A=diff * 10;
            if(map.find(diff)!=map.end())break;
            else map[diff]=res.length();
        }
        res.insert(map[diff],"(");
        res+=")";
        return res;
    }
    };

Log in to reply
 

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