c++ solution


  • 0
    B

    1 use long to avoid exceed
    2 denominator could be negative

    class Solution {
    public:
        string fractionToDecimal(int numerator, int denominator) {
         unordered_map<long,int> mp;
         long a=labs(numerator),b=labs(denominator),r=a%b;
         string result;
         
         if ((numerator<0)^(denominator<0) && numerator!=0) result+='-';
         result+=to_string(a/b);
         
         if(r==0) return result;
         
         result+='.';
         
         int i=result.length();
         
         while(r!=0){
             mp[r]=i++;
             result+=to_string(r*10/b);
             r=r*10%b;
             
             if(mp.find(r)!=mp.end()){
                 result.insert(mp[r],"(");
                 result+=')';
                 return result;
             }
             
         }
         
         return result;
        }
    };
    
    

Log in to reply
 

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