[Naive Approach] By Repeated Subtraction - O(a/b) Time and O(1) Space
The basic idea is to first find the sign of quotient. The sign of the quotient will be negative only when the sign of dividend and divisor are different. Now, convert both the dividend and divisor to positive numbers and keep subtracting the divisor from the dividend until the dividend becomes less than the divisor. The dividend becomes the remainder, and the number of times subtraction is done becomes the quotient. Finally, we append the sign to the quotient to get the final result.
This approach fails for large values of quotient.
Output
-5
Time complexity: O(a/b), where a is the dividend and b is the divisor. Auxiliary space: O(1)
[Expected Approach] Using Bit Manipulation - O(log(a)) Time and O(1) Space
The idea is similar to the previous approach with the only difference that instead of subtracting one unit of divisor from the dividend, we can subtract multiple units of divisor at once until the dividend becomes smaller than divisor.
This can be easily done by iterating on the bit position i = 30 to 0. For each bit position i, where (divisor << i) is less than dividend, set the ith bit of the quotient and subtract (divisor << i) from the dividend. After iterating over all the bits, return the quotient with the corresponding sign.
Output
-5
Time Complexity: O(log(a)), as we are iterating over all the bits of a. Auxiliary Space: O(1)