LeetCode Divide Two Integers

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.

Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 =
truncate(3.33333…) = 3. Example 2:

Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 =
truncate(-2.33333…) = -2. Example 3:

Input: dividend = 0, divisor = 1 Output: 0

Input: dividend = 1, divisor = 1 Output: 1

public:
    int divide(int dividend, int divisor) {
            if (dividend == 0)
               return 0;
            if (dividend == INT_MIN && divisor == -1)
                return INT_MAX;
            if (dividend == INT_MIN && divisor == 1)
                return INT_MIN;
            long a = fabs(dividend);
            long b = fabs(divisor);
            bool sign = false;
            if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
                sign = true;
            int res = div(a, b);
            if (sign)
                return -res;
            else return res;
    }
    int div(long a, long b){
        if (a < b)
            return 0;
        if (a == b)
            return 1;  
        long base = b;
        int cnt = 1;
        while ((base + base) <= a){
            cnt = cnt + cnt;
            base = base + base;
        }
        return cnt + div(a - base, b);
    }
};

不能使用乘法和除法,那就除数每轮加上它本身即可得到倍乘,若结果小于被除数,则继续,否则回退一轮,用被除数减去的结果继续,如16除3
第一步将3 + 3 意味着 3 * 2 得 6 < 16 继续
第二步将6 + 6 意味着 3 * 4 得 12 < 16 继续
第三步将12 + 12 意味着 3 * 8 得 24 > 16 回退
所以结果 在4和8 之间
第四步将16-12 得 4
然后继续将4和3重复上轮循环
看下面代码

   int div(long a, long b){
        if (a < b) //当被除数小于除数后结果为0
            return 0;
        if (a == b) //若相等则结果为1
            return 1;  
        long base = b;
        int cnt = 1; //以上结果排除后则a必定大于b,结果至少为1
        while ((base + base) <= a){ //倍乘了
            cnt = cnt + cnt; 
            base = base + base;
        }  
        return cnt + div(a - base, b);
    }

因为返回值为int型,所以若被除数为INT_MIN,除数为-1时,结果为INT_MAX+1, 会发生溢出,所以要提前判定。当被除数为INT_MIN,
除数为1时,在 cnt 这里会溢出,所以也要提前判定

   while ((base + base) <= a){ //倍乘了
            cnt = cnt + cnt;  
            base = base + base;
        }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值