码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 29. 两数相除 Divide Two Integers

时间:2020-05-31 18:17:56      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:color   问题   返回   src   etc   sig   col   res   ret   

技术图片

 

 使用了long。没有解决int的溢出问题。

class Solution {
public:
    int divide(int dividend, int divisor) {
        //if (dividend == 0) return 0;
        //if (divisor == 1) return dividend;
        if (divisor == -1)
        {
            //只要不是最小整数,直接返回相反数
            if (dividend > INT_MIN) return -dividend;
            return INT_MAX;  //最小整数返回最大整数
        }

        long a = dividend;  //处理溢出
        long b = divisor;
        int sign = 1;
        if ((a > 0 && b < 0) || (a < 0 && b > 0))  //异号
            sign = -1;
        a = a > 0 ? a : -a;
        b = b > 0 ? b : -b;
        long res = div(a, b);
        if (sign > 0) return res > INT_MAX ? INT_MAX : res;
        return -res;
    }
    int div(long a, long b)
    {
        if (a < b) return 0;
        long cnt = 1;
        long tb = b;
        while ((tb + tb) <= a)  //加法代替乘法
        {
            cnt = cnt + cnt;
            tb = tb + tb;
        }
        return cnt + div(a - tb, b);
    }
};

 

LeetCode 29. 两数相除 Divide Two Integers

标签:color   问题   返回   src   etc   sig   col   res   ret   

原文地址:https://www.cnblogs.com/ZSY-blog/p/13019715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!