标签: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