
Sponsored
Sponsored
This approach uses repeated subtraction to calculate the quotient. The idea is to keep subtracting the divisor from the dividend until the dividend
Time Complexity: O(n), where n is the result of the division. This can be inefficient for large numbers.
Space Complexity: O(1), as no extra space is used.
1#include <limits.h>
2
3int divide(int dividend, int divisor) {
4 if (divisor == 0) return INT_MAX;
5 if (dividend == INT_MIN && divisor == -1) return INT_MAX;
6 int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
7 long long ldividend = llabs((long long)dividend);
8 long long ldivisor = llabs((long long)divisor);
9 int quotient = 0;
10 while (ldividend >= ldivisor) {
11 ldividend -= ldivisor;
12 ++quotient;
13 }
14 return sign * quotient;
15}The C code starts by checking for division by zero or the special overflow case where the dividend is INT_MIN and the divisor is -1. It calculates the result's sign based on the input signs.
Using long long for the absolute values ensures no overflow. While the dividend is greater than or equal to the divisor, it deducts the divisor from the dividend and increments the quotient.
Finally, it applies the sign to the quotient and returns the result.
Bit manipulation provides an optimized method to divide without causing repeated subtractions. By efficiently finding how many times the divisor can be shifted left (multiplied by two) in the dividend range, we can ascertain parts of the quotient to sum incrementally. This halves the number of operations compared to repeated subtraction.
Time Complexity: O(log n), where n is the approximate number of bits in the dividend with respect to bit manipulation.
Space Complexity: O(1), as shifts occur without additional structures.
1
This C solution utilizes bit shifting to match divisor powers of 2 and left shifts while deducting divisor multiplicities from the dividend. It results in a multistage process of merging high bits calculation primarily through shift comparisons between divisor equivalences.