59. Divide Two Integers
- Divide Two Integers My Submissions QuestionEditorial Solution
Total Accepted: 66073 Total Submissions: 421509 Difficulty: Medium
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路:每次减去b(同时b不断的翻倍,从1,2,2^2…)
为什么这样是可行的,因为如果a=nb+x
那么n作为一个整数一定是可以表示成
所以从
#define IMAX numeric_limits<int>::max()
#define IMIN numeric_limits<int>::min()
class Solution {
public:
int divide(int dividend,int divisor) {
assert(divisor!=0);
int sign = (dividend<0&&divisor>0||dividend>0&&divisor<0)?-1:1;
unsigned int a = dividend<0?-dividend:dividend;
unsigned int b = divisor<0?-divisor:divisor;
unsigned int c = b;
int multi=0;
while(a>=b){
int i=1;
while(a>=b){
a -=b;
multi+=i;
if(b<IMAX>>1){
b=b<<1;
i<<=1;
}
}
b=c;
}
if(sign>0&&multi==IMIN)return IMAX;
else return multi*sign;
}
};