Why I cannot use int in my while loop


  • 0
    L
    class Solution {
    public:
        int divide(int dividend, int divisor) {
    
            int ret = 0;
            int sign = 1;
            if (dividend<0){sign = -sign;}
            if (divisor<0){sign = -sign;}
             
            unsigned long long tmp = abs((long long)dividend);
            unsigned long long tmp2 = abs((long long)divisor);
            while (tmp>=tmp2) {
                *****//unsigned long long d=tmp2;
                int d = tmp2;*****
                int r=1;
                while (tmp-d>=d){
                    d+=d;
                    r+=r;
                }
                tmp=tmp-d;
                ret+=r;
            }
            return ret*sign;
        }
    };
    

    if I use "int d=tmp2", the test case will fail on (-2147483648, 1). But if I change back to "unsigned long long d=tmp2;", it will pass. I cannot find out where the problem is.


  • 0
    M

    int, Signed: From −2,147,483,648 to 2,147,483,647.

          while (tmp-d>=d){
                d+=d;
                r+=r;
            }
    

    so d could be 2,147,483,648 here?


  • 0
    L

    you mean when d adds up to 2,147,483,648, it is wrapped up to INT_MIN, -2,147,483,648. then it is stuck to this value. so the while loop continues ?


Log in to reply
 

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