Leetcode Divide Two Integers Problem Solution

In this Leetcode Divide Two Integers Problem Solution Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.

Return the quotient after dividing dividend by divisor.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.

Leetcode Divide Two Integers Problem Solution


Problem solution in Python.

class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        a, b, r, t = abs(dividend), abs(divisor), 0, 1
        while a >= b or t > 1:
            if a >= b: r += t; a -= b; t += t; b += b
            else: t >>= 1; b >>= 1
        return min((-r, r)[dividend ^ divisor >= 0], (1 << 31) - 1)

Problem solution in Java.

public class Solution {
    public int divide(int dividend, int divisor) {
		//all of these if else statements are only for edge cases and to make both dividend and divisor negative
        if (dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;
        if (divisor == 1)
            return dividend;
        if (dividend > 0 && divisor > 0)
            return divide(-dividend, -divisor);
        else if (dividend > 0)
            return -divide(-dividend, divisor);
        else if (divisor > 0)
            return -divide(dividend, -divisor);
        if (divisor < dividend || dividend == 0)
            return 0;
        int sum = divisor;
        int mult = 1;
        while ((sum + sum) < sum && (sum + sum) >= dividend) {
            sum += sum;
            mult += mult;
        }
        return mult + divide(dividend - sum, divisor);
    }
}


Problem solution in C++.

class Solution {
public:
    int divide(int dividend, int divisor) {
        int res = 0;
        
        if (1 == divisor)
            return dividend;
        
        if (-1 == divisor)
            return dividend == std::numeric_limits<int>::min() ? std::numeric_limits<int>::max() : -dividend;
        
        if (1 == dividend)
            return 0;
        
        bool const sign = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0);
        
        using op_t = std::function<int(int, int)>;
        auto op = sign ? op_t(std::plus<int>()) : op_t(std::minus<int>());
        
        std::stack<std::pair<int64_t, int>> st;
        st.push({divisor, 1});
        
        while (!st.empty())
        {
            while (std::abs(dividend) >= std::abs(st.top().first))
            {
                auto [dev, inc] = st.top();
                dividend = op(dividend, dev);
                res += inc;
                st.push({dev + dev, inc + inc});
            }
            st.pop();
        }
 
        return sign ? -res : res;
    }
};


Problem solution in C.

inline uint32_t uabs(int i)
{
    return i < 0 ? ~(uint32_t) i + 1 : i;
}
 
int divide(int dividend, int divisor) {
    // Get rid of signs because bitwise math is easier with positive numbers
    uint32_t remainder = uabs(dividend);
    uint32_t positiveDivisor = uabs(divisor);
    
    // Long division algorithm everyone learned in grade school, except in binary instead of decimal
    uint32_t result = 0;
    for (int i = 31; i >= 0; --i) {
        uint32_t curDividend = remainder >> i;
        if (curDividend >= positiveDivisor) {
            result += 1u << i;
            remainder -= positiveDivisor << i;
        }
    }
    
    // Reintroduce the sign as appropriate
    if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
        return result >= (uint32_t) INT_MAX ? INT_MAX : (int) result;
    }
    else {
        // Invert bits and add one instead of multiplying by -1
        return result > (uint32_t) INT_MAX ? INT_MIN : ((int) ~result) + 1;
    }
}


Post a Comment

0 Comments