Numerator = -1 and denominator = -2147483648, why "0.0000000000000000000000000000001"?


  • 0
    K
    class Solution {
    public:
        string fractionToDecimal(int numerator, int denominator) {
            if(numerator == 0)
                return "0";
            string ret;
            if(numerator<0 ^ denominator<0)
                ret += '-';
            int n = abs(numerator), d = abs(denominator);
            ret += to_string(n/d);
            if(int r = n%d)
            {
                ret += '.';
                unordered_map<int, int> m;
                for(; r; r%=d)
                {
                    if(m.count(r))
                    {
                        ret.insert(m[r], 1, '(');
                        ret += ")";            
                        break;
                    }
                    m[r] = ret.size();
                    r*=10;
                    ret += to_string(r/d);
                }
            }
            return ret;
        }
    };
    

    I already solved this problem by changing int to long.
    I know the abs(-2147483648) is still -2147483648.
    I'm just wondering why the above code gives out 0.0000000000000000000000000000001.
    Thanks in advance for your explanation.


  • 0
    Z
    This post is deleted!

  • 0
    N

    Note that the number "-2147483648" may overflow if we define the type of the denominator as "int".
    I guess that it may be a bug.
    Just change the type of numerator and denominator to "long long" to meet.
    Be careful that some related data's type in your function should also be changed.
    Hope it will be helpful.


  • 0
    S
    int n = abs(numerator), d = abs(denominator)
    

    here, try long and change accordingly


  • 0
    X
    This post is deleted!

Log in to reply
 

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