Leetcode#29 Divide Two Integers

原创 2015年07月10日 21:02:33

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

If it is overflow, return MAX_INT.

Difficulty:Medium

要解决的问题有两个:

1.溢出的情况是在-2147483648却绝对值的时候,用long long就好

2.一个个减会超时。利用位移,每次减的都是上次的两倍,大大缩短时间,利用循环解决。

int divide(int dividend, int divisor) {
        if(dividend ==-2147483648 &&divisor ==-1)
            return 2147483647;
        if(dividend==0||divisor==0)
            return 0;
        if(divisor==1)
            return dividend;
         else if(divisor == -1)
            return -dividend;
        int cou = 0, flag1 = 0,flag2 = 0;
        long long a = dividend;
        long long b = divisor;
        if(a<0)
        {
            a = 0-a;
            flag1 = 1;
        }
        if(b<0)
        {
            b = 0 - b;
            flag2 = 1;
        }
        while(a>=b)
        {
            long long c = b;
            for(int i = 0; a>=c; i++,c<<=1)
            {
               a = a-c;
               cou = cou + (1<<i);
            }
        }

        if(flag1==flag2)
            ;
        else
            cou = -cou;
        return cou;
    }


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

相关文章推荐

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

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

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

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

[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]29.Divide Two Integers

【题目】 Divide two integers without using multiplication, division and mod operator. If it is overfl...

leetcode:29. Divide Two Integers

描述: Divide two integers without using multiplication, division and mod operator.If it is overflow, r...

LeetCode 29 Divide Two Integers(两个整数相除)(*)

翻译不用乘法、除法、取余操作,将两个数相除。如果它溢出了,返回MAX_INT原文Divide two integers without using multiplication, division a...
  • NoMasp
  • NoMasp
  • 2015-11-17 20:04
  • 3613

LeetCode 29. Divide Two Integers

LeetCode 29. Divide Two Integers C++位运算

Leetcode-29. Divide Two Integers

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

Leetcode29. Divide Two Integers

29. Divide Two Integers内容如下: Divide two integers without using multiplication, division and mod ope...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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