Accepted cpp solution, without converting int to long long


  • 0
    Z
    const int shift = sizeof(int) * 8 - 1;
    class Solution {
    public:
    string fractionToDecimal(int numerator, int denominator) {
        string res = "";
        if(numerator && denominator && 
           (numerator >> shift) ^ (denominator >> shift)){
            res = "-";   
        }
        int remainder = 0;
        if(numerator == INT_MIN && abs(denominator) == 1)
        {
            res += to_string(INT_MIN);
            res.erase(0,1);
        }else{
            res += to_string(abs(numerator / denominator));
            remainder = abs(numerator % denominator);
        }
        if(remainder){            
            res += ".";
            unordered_map<int,int> repeat;
            for(int curPos = res.length(); remainder; curPos++){
                if(repeat.count(remainder)>0){
                   res.insert(repeat[remainder],"(");
                   res.push_back(')');
                   return res;
                }
                repeat[remainder]=curPos;
                int tmpRes = 0;
                if(!(denominator / 10)){
                   remainder *= 10;
                   tmpRes = abs(remainder/denominator);
                   remainder = abs(remainder % denominator); 
                }else{
                   int tmpDenominator = abs(denominator / 10), digit = abs(denominator % 10), tmpRemainder;
                   tmpRes = remainder / tmpDenominator;
                   tmpRemainder = (remainder - digit * tmpRes / 10 - tmpRes * tmpDenominator)*10 - (digit * tmpRes) % 10;
                   while(tmpRemainder >> shift){
                       tmpRes--;
                       tmpRemainder = (remainder - digit * tmpRes / 10 - tmpRes * tmpDenominator)*10 - (digit * tmpRes) % 10;
                   }
                   remainder = tmpRemainder;
                }
                res += to_string(tmpRes);
            }           
        }
        return res;
     }
    };

Log in to reply
 

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