C++ School math solution


  • 0
    G
    class Solution {
    public:
        int divide(int dividend, int divisor) 
        {
            long long Res = 0;
            long long Div = 0;
            long long dividend2 = ((long long)dividend);
            long long divisor2 = ((long long)divisor);
            
            bool Sign = ((dividend2 < 0) ^ (divisor2 < 0));
            
            dividend2 = abs(dividend2);
            divisor2 = abs(divisor2);
        
            for (int i = 31; i >= 0; --i)
            {
                Div = (Div << 1) | ((dividend2 & (1 << i)) >> i);
                Res <<= 1;
        
                if (Div >= divisor2)
                {
                    Res |= 1;
                    Div -= divisor2;
                }
            }
        
            return (Sign == true ? (Res*-1 < INT_MIN ? INT_MAX : -Res) : (Res > INT_MAX ? INT_MAX : Res));
        }
    };

Log in to reply
 

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