//C++代码不支持左移运算 程序暂时有问题,之后再来排查 class Solution { public: int divide(int dividend, int divisor) { if(dividend == INT_MIN && divisor == -1) return INT_MAX;//除法结果溢出的处理 // 特殊情况,无需计算,直接返回 if (dividend == 0 || divisor == 1) { return dividend; } else if (divisor == -1) { return -dividend; }
int flag = 0; if (dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0) flag = 1; //除数与被除数转为负数防止溢出 if (dividend > 0) dividend = -dividend; if (divisor > 0) divisor = -divisor;
unsigned int res = divideCore(dividend, divisor); return flag ? -res : res; }
int divideCore(int dividend, unsigned int divisor) { // 被除数 == 除数,直接返回结果为 1 if (dividend == divisor) { return 1; } // 开始正式计算 unsigned int result = 0; int shift = getMaxShift(divisor, dividend);
while (dividend <= divisor) { while (dividend > (divisor << shift)) shift--; dividend -= (divisor << shift); result += (1 << shift); } return result; }
int getMaxShift(int num, int min) { // num 是除数,min 是被除数,希望找到 num << shift < min 时,shift 的最大值 int shift = 0; unsigned int temp = num; while (temp > min && temp >= (INT_MIN >> 1)) { temp <<= 1; shift++; } return shift; } }; class Solution { public int divide(int a, int b) { //特殊情况1, b=1 if (b == 1){ return a; } //特殊情况2, b=-1 if (b == -1){ return a == Integer.MIN_VALUE ? Integer.MAX_VALUE : -a; } //特殊情况3, a=0 if (a == 0){ return 0; }
//确定符号 boolean positive = (a ^ b) >= 0; //为避免溢出, 转换为负数进行计算 a = a < 0 ? a : -a; b = b < 0 ? b : -b; //快速相减 int quotient = 0; while (a <= b){ int base = 1; int divisor = b; //使用减法, 避免溢出 while (a - divisor <= divisor){ divisor <<= 1; base <<= 1; } quotient += base; a -= divisor; } return positive ? quotient : -quotient; } }