Divide Two Integers(math)

The integer division should truncate toward zero.

Example 1:

Input:
 dividend = 10, divisor = 3

Output:
 3

Example 2:

Input:
 dividend = 7, divisor = -3

Output:
 -2

Note:

Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

分析

先都abs,注意 Map: p,q,i,ans =map(abs,(dividend, divisor,0,0))

divident = divisor*(1+2+4+6+8.....)

注意其实<< >>就是 *2和//2。 ans = 1+2+4+6+8.....

Time: O(log(answer)) = O(log(dividend // divisor)) = O(log(dividend) - log(divisor))

Space: O(1)

注意这里判断2个异号的方法 :

(dividend<0)!=(divisor<0)

还有就是int的取值

Last updated

Was this helpful?