Divide Two Integers Algorithm

The Divide Two Integers Algorithm is a computational method used to perform division operations on two integer numbers without relying on the built-in division or multiplication operators. This algorithm leverages the concept of bit manipulation and bitwise operations, which are efficient and faster than the traditional arithmetic operations. The primary idea behind this algorithm is to incrementally subtract the divisor from the dividend and count the number of times the subtraction occurs before the dividend becomes smaller than the divisor. This count represents the quotient of the division, while the remaining dividend represents the remainder. To implement the Divide Two Integers Algorithm, the user must have a clear understanding of binary numbers and bitwise operations such as left and right shifts. The algorithm starts by identifying the sign of the result based on the signs of the input integers (i.e., positive, negative, or zero). Then, the algorithm converts both dividend and divisor into their absolute values, as bitwise operations work with non-negative numbers. Next, the algorithm iteratively performs a left shift operation on the divisor until the shifted divisor becomes greater than the dividend. Then, the algorithm performs right shift operations on the divisor while subtracting the shifted divisor from the dividend and incrementing the quotient count. The process continues until the divisor can no longer be subtracted from the dividend. Finally, the algorithm returns the calculated quotient and applies the correct sign based on the initial sign calculation.
class Solution {
public:
    int divide(int dividend, int divisor) {
        long long int divid = dividend;
        long long int divis = divisor;
        bool neg = false;
        if (divid < 0) {
            neg = neg ? false : true;
            divid = -divid;
        } 
        if (divis < 0) {
            neg = neg ? false : true;
            divis = -divis;
        }
        long long int result = 0;
        while (divid >= divis) {
            long long int x = divis;
            int shift = 0;
            while ((x << 1) <= divid) {
                x <<= 1;
                shift += 1;
            }
            result += 1 << shift;
            divid -= x;
        }
        if (neg) {
            result = -result;
        }
        return result;
    }
};

LANGUAGE:

DARK MODE: