29_Divide Two Integers
[Medium] [Math, Binary Search]
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend
by divisor
. The integer division should truncate toward zero.
Example 1:
Example 2:
Solution 1: Linear Search
Idea:
Deduct divisor from dividend many times. Record how many times it takes until dividend is less than divisor.
Time Complexity: , where n is the output (quotient).
Space Complexity:
Solution 2: Binary Search ??
整数近似除法:32/3 = 10
显然求近似除法可以用乘法来二分查找:32 ~ 3*10 = 3*[1*(2^3) + 0*(2^2) + 1*(2^1) + 0*(2^0)]
res = 0
先找到a使x*2^a <= y < x*2^(a+1),res += 2^a,y = y - x*2^a
if(y >= x*2^(a-1) {res+=2^(a-1); y = y - x*2^(a-1);}
if(y >= x*2^(a-2) {res+=2^(a-2); y = y - x*2^(a-2);}
...
但题目不允许用乘法,可以用移位代替:x*2^i = x<<i:
Time Complexity: , where n is the output (quotient).
Space Complexity:
Last updated