题目链接:https://leetcode.com/problems/divide-two-integers/
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
int divide(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) //被除数为-2147483648除数为-1时,商溢出 return INT_MAX; int quotient = 0; int flag = (dividend>0&&divisor>0 || dividend<0&&divisor<0) ? 1 : -1; unsigned int a = dividend > 0 ? dividend : -dividend; //无符号整数防止-2147483648取绝对值后溢出 unsigned int b = divisor > 0 ? divisor : -divisor; unsigned int tmp = a; int digit = 0; //商的二进制位数 while(tmp >= b) { //计算商的二进制位数 ++digit; tmp >>= 1; } while(digit--) { //类似除法的笔算过程,从最高位开始除算出商的各个位数上的数值 unsigned int divi = b << digit; //在除数后面补0使得除被除数得到个位数 quotient = (quotient << 1) + (a >= divi ? 1 : 0); //高位的商移位后要加权(左移加权2) a = a >= divi ? a - divi : a; } if(flag < 0) quotient = -quotient; return quotient; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ice_camel/article/details/46959549