Leetcode 29. 两数相除 题解

题目链接:https://leetcode-cn.com/problems/divide-two-integers/
在这里插入图片描述
二分,与模版不同的是,这次的二分左右指针实际上是被除数和除数,例如示例1中,先判断10 > 3,则再判断 10 > 6? 再判断 10 > 12? 以此类推(相当于右指针 * 2),当判断大于为否后,将被除数减去最大已知的幂次,再继续循环(相当于左指针 - 右指针),以此类推。

判断越界比较麻烦,我干脆直接用 long 型去维护,最后直接对结果是否越界做判断

代码如下:

class Solution {
public:
    long solve(long a, long b) {
        printf("a = %d, b = %d\n", a, b);
        if(a < b) {
            return 0;
        } else if(a == b) {
            return 1;
        } else {
            long ans = 1;
            long pos = b;
            long now = b;
            b += b;
            while(a > b) {
                ans += ans;
                now = b;
                b += b;
            }
            printf("now = %d, pos = %d, ans = %d\n", now, pos, ans);
            ans += solve(a - now, pos);
            return ans;
        }
    }
    
    int divide(int dividend, int divisor) {
        bool flag1, flag2, flag;
        flag1 = (dividend < 0);
        flag2 = (divisor < 0);
        flag = flag1 ^ flag2;
        //同号则 flag = 0, 异号则 flag = 1

        long a = abs(dividend), b = abs(divisor);
        printf("被除数 = %d, 除数 = %d, flag = %d\n", a, b, flag);
        long res = solve(a, b);
        res = flag == 1 ? res * -1: res;
        if(res > INT_MAX || res < INT_MIN) {
            return INT_MAX;
        } else {
            return res;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42396397/article/details/105935126