给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
返回被除数 dividend 除以除数 divisor 得到的商。
示例 1:
输入: dividend = 10, divisor = 3
输出: 3
示例 2:
输入: dividend = 7, divisor = -3
输出: -2
int divide(int dividend, int divisor) { int count=0; if((dividend>INT32_MAX||dividend<INT32_MIN)||(divisor>INT32_MAX||divisor<INT32_MIN)) return INT32_MAX; if((dividend)==INT32_MIN&&(divisor==INT32_MIN)) return 1; if((dividend)==INT32_MIN&&(divisor==1)) return INT32_MIN; if(divisor==INT32_MIN) return 0; if((dividend)==INT32_MIN&&(divisor==-1)) return INT32_MAX; if(dividend==INT32_MIN) { bool flag=0; if(divisor<0) flag=1; divisor=(divisor>0)?divisor:-divisor; while(dividend<=0) { dividend+=divisor; count++; } return flag?count-1:1-count; } if(dividend==0||abs(dividend)<abs(divisor)) return count; if(divisor==1) return dividend; if(divisor==-1) return -dividend; else if(dividend>0&&divisor>0||dividend<0&&divisor<0) { dividend=abs(dividend); divisor=abs(divisor); while (dividend>=0) { dividend-=divisor; count++; } return (count-1); } else if(dividend<0&&divisor>0||dividend>0&&divisor<0) { dividend=(dividend>0)?dividend:-dividend; divisor=(divisor>0)?divisor:-divisor; while (dividend>=0) { dividend-=divisor; count++; } return 1-count; } return 0; }