美文网首页
29. 两数相除 leetcode

29. 两数相除 leetcode

作者: 出来遛狗了 | 来源:发表于2018-11-02 11:02 被阅读0次
    image.png
    class Solution {
        func divide(_ dividend: Int, _ divisor: Int) -> Int {
            if dividend == 0{
                return 0;
            }
            var isNeed = false
            var dividend = dividend;
            var divisor = divisor;
            if dividend > 0 && divisor < 0{
                isNeed = true
                divisor = 0 - divisor;
            }else if dividend < 0 && divisor > 0{
                isNeed = true
                dividend = 0 - dividend;
            }else if dividend < 0 && divisor < 0{
                divisor = 0 - divisor;
                dividend = 0 - dividend;
            }
            if divisor == 1{
                
                if isNeed {
                    return Int(Int32(0 - dividend));
                }else{
                    if dividend >= 2^31{
                        return Int(Int32.max)
                    }
                    return Int(Int32(dividend));
                }
            }
            var i = 0;
            while divisor <= dividend {
                var temp = divisor;
                var cnt = 1;
                while dividend >= temp{
                    temp = temp<<1
                    cnt = cnt<<1
                }
                i += (cnt>>1)
                dividend -= (temp>>1)
            }
            if isNeed {
                return Int(0 - i);
            }else{
                return Int(i);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:29. 两数相除 leetcode

          本文链接:https://www.haomeiwen.com/subject/dpmqxqtx.html