Problem 716
Divide Two Integers
Medium · 20 pts · Math, Bit Manipulation
Problem
Divide integer A by integer B and print the quotient truncated toward zero (so 7 / -2 gives -3), without using multiplication, division or the modulo operator. The result must fit a signed 32-bit integer: if it is greater than 2^31 - 1, print 2^31 - 1 instead. Work with absolute values and subtract the largest shifted copies of the divisor (B << k) that still fit, adding 2^k to the quotient each time.
Input
A single line with two integers A and B.
Output
Print the truncated quotient, clamped to the 32-bit range.
Constraints
-2^31 <= A, B <= 2^31 - 1; B != 0
Example input
10 3
Example output
3
Explanation
10 / 3 is 3.33..., which truncates to 3. For 7 and -3 the true quotient is -2.33..., which truncates toward zero to -2.