Swift solution - Binary Search


  • 0
    class Solution {
        func divide(_ dividend: Int, _ divisor: Int) -> Int {
            let sign: Int64 = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0) ? 1 : -1
            let lDividend = dividend < 0 ? -Int64(dividend) : Int64(dividend)
            let lDivisor = divisor < 0 ? -Int64(divisor) : Int64(divisor)
            var result: Int64 = 0
            var left: Int64 = 1
            var right: Int64 = lDividend
            var middle: Int64 = 0
            
            while left <= right {
                middle = (left + right) / 2
                if middle * lDivisor <= lDividend {
                    result = middle
                    left = middle + 1
                } else {
                    right = middle - 1
                }
            }
            
            return result * sign == Int64.max ? Int.max : Int(result * sign)
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.