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:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
花花酱解题视频
func divide(dividend int, divisor int) int {
sign := 1
if (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) {
sign = -1
}
if dividend == 0 {
return 0
}
absDividend, absDivisor := int64(math.Abs(float64(dividend))), int64(math.Abs(float64(divisor)))
res := dfs(absDividend, absDivisor)
if res > math.MaxInt32 {
if sign == -1 {
return math.MinInt32
} else {
return math.MaxInt32
}
}
return int(res) * sign
}
func dfs(dividend int64, divisor int64) int64 {
if dividend < divisor {
return 0
}
_sum, mul := divisor, int64(1)
for _sum+_sum <= dividend {
_sum += _sum
mul += mul
}
return mul + dfs(dividend-_sum, divisor)
}