[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-29] Divide Two Integers(两个整数相除,不用乘除取余算术符)

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

[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 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...

leetcode:Divide Two Integers

一、 题目 不使用乘法、除法、求余运算实现除法运算,除数和被除数、结果都是用int型。 如果溢出就返回MAX_INT。 二、 分析 看到题目后我立马想到了计算机组成原理中的一位除法和二位除法,...

Leetcode || Divide Two Integers

Divide two integers without using multiplication, division and mod operator.If it is overflow, retur...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[Leetcode]Divide Two Integers
举报原因:
原因补充:

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