LeetCode #29 Divide Two Integers

LeetCode #29 Divide Two Integers

Question

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

Solution

Approach #1

class Solution {
    func divide(_ dividend: Int, _ divisor: Int) -> Int {
        let max = Int(Int32.max)
        if divisor == 0 || (dividend == Int(Int32.min) && divisor == -1) { return max }
        let positive = (dividend < 0) == (divisor < 0)
        var a = abs(dividend)
        let b = abs(divisor)
        var r = 0
        while a >= b {
            var accumulateB = b
            var toAdd = 1
            while a >= accumulateB {
                a -= accumulateB
                r += toAdd
                accumulateB <<= 1 // accumulateB += accumulateB
                toAdd <<= 1 // toAdd += toAdd
            }
        }
        return positive ? r : -r
    }
}

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7067196.html

posted on 2017-06-23 22:20  Silence_cnblogs  阅读(230)  评论(0编辑  收藏  举报