- Divide Two Integers
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: 3Example 2:
Input: dividend = 7, divisor = -3
Output: -2Note:
- 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.
简单来说就是不用‘乘法’、‘除法’和‘取余’运算来求两个整数的商,注意结果要在 [−231, 231 − 1]
Round One
- 暴力减法(如下),我赌5毛,超时(Time Limit Exceeded)!
// Swift Code
class Solution {
func divide(_ dividend: Int, _ divisor: Int) -> Int {
let sign = (dividend >= 0) == (divisor > 0) ? 1 : -1
var dividend = abs(dividend)
let divisor = abs(divisor)
var result = 0
while dividend > divisor {
dividend -= divisor
result += 1
}
if dividend == divisor {
result += 1
}
return sign < 0 ? -result : result
}
}
Round Two
一个一个减肯定是超时了,要是一批一批减呢?
所以就需要先成倍放大被除数,不允许用‘乘法’、‘除法’和‘取余’ 还有 ‘<<’、‘>>’
// Swift Code
class Solution {
func divide(_ dividend: Int, _ divisor: Int) -> Int {
// 除数、被除数符号不一致时候商为负数
let sign = (dividend >= 0) == (divisor > 0) ? 1 : -1
// 扩大下数据类型,避免溢出
var _dividend = Int64(abs(dividend))
let _divisor = Int64(abs(divisor))
var result = 0
var temp = 1
var _divisor_temp = _divisor
// 放大被除数
while _divisor_temp < _dividend {
_divisor_temp = _divisor_temp << 1
temp = temp << 1
}
// 在合理范围内缩小被放大的被除数
while _divisor_temp > 0, _divisor_temp > _divisor {
while _divisor_temp > _dividend {
_divisor_temp = _divisor_temp >> 1
temp = temp >> 1
}
_dividend -= _divisor_temp
result += temp
}
// 竟然一样大,所以再来一次了
if _dividend == _divisor {
result += 1
}
// 结果是有范围限制的
return sign < 0 ? max(-result, Int(Int32.min)) : min(result, Int(Int32.max))
}
}
TestCase
// Swift Code
assert(Solution().divide(10, 3) == 3)
assert(Solution().divide(3, 3) == 1)
assert(Solution().divide(1, 1) == 1)
assert(Solution().divide(2, 3) == 0)
assert(Solution().divide(7, -3) == -2)
assert(Solution().divide(-2147483648, -1) == 2147483647)
assert(Solution().divide(0, 2147483648) == 0)