Divide Two Integers
https://leetcode.com/problems/divide-two-integers/description/
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Thoughts
不用任何乘,除和mod操作实现实现除法。除法本质上是数dividend由多少个divisor相加可构成。比如32 = 24 + 8 = 3 * 2^3 + 3 * 2 + 2。而divisor * 2^i可以通过位左移得到,因此不断让divisor左移cnt次, 直到超过dividend,然后让dividend减去divisor * 2^(cnt - 1),再重复此过程直到dividend比divisor还小。
Code
Analysis
divisor * 2 ^ t = dividend, 时间复杂度O(lgN)
Last updated
Was this helpful?