[Leetcode]Divide Two Integers

原创 2015年11月19日 15:11:26

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

If it is overflow, return MAX_INT.


class Solution {
public:
    /*algorithm binary search 
    */
    int bSearch(long d1,long d2){
        long l = 1,h = d1;
        while(l <= h){
            long m = (l+h)>>1;
            long d = d1 - m*d2;
            if(0 <= d && d < d2){
                return m;
            }else if(d >= d2){
                l = m+1;
            }else{
                h = m-1;
            }
        }
    }
    int divide(int dividend, int divisor) {
        long d1 = labs(dividend),d2 = labs(divisor);//use labs,instead of abs,or -
        bool neg = (dividend^divisor)>>sizeof(int)*8-1;//d1<0&&d2 >0 || d1>0||d2<0
        if(d1 == 0 || d1 < d2)return 0;
        if(d2 == 1 && d1 > INT_MAX)return neg?-d1:INT_MAX;
        long count=bSearch(d1,d2);
        return neg?-count:count;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

[LeetCode]029-Divide Two Integers

题目: Divide two integers without using multiplication, division and mod operator.If it is overflow, ...

LeetCode 之 Divide Two Integers

LeetCode 之 Divide Two Integers Divide two integers without using multiplication, division and mod ...

LeetCode 29 Divide Two Integers (C,C++,Java,Python)

Problem: Divide two integers without using multiplication, division and mod operator. If it ...

【leetcode】Divide Two Integers

题目:不用乘、除、取模运算来实现除法。 减法可以实现除法在是我们早就知道的,但是可能会出现问题,比如极端情况,a = 0x7FFFFFFF,b = 1,求a/b,这要减法运算多少次? 回想下我们开...

leetcode笔记:Divide Two Integers

题目的意思简单明了,就是要求不使用乘法、除法和取余mod,输入两个整数,输出除法操作的结果。

leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法

Divide Two Integers  Divide two integers without using multiplication, division and mod operato...

LeetCode Divide Two Integers

Description: Divide two integers without using multiplication, division and mod operator. If it i...

[LeetCode-29] Divide Two Integers(两个整数相除,不用乘除取余算术符)

Divide two integers without using multiplication, division and mod operator.If it is overflow, retur...

LeetCode(29)Divide Two Integers

题目内容 Divide two integers without using multiplication, division and mod operator. 题目分析 最容易的想到的办法,是把...

《leetCode》:Divide Two Integers

题目Divide two integers without using multiplication, division and mod operator.If it is overflow, ret...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)