【LeetCode】29. Divide Two Integers
Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
不能用乘法,我们可以移位啊,移p位就相当于乘了2p
举例说明我的方法:
f(24,5)=24/5=20/5+4/5=4+0=4
5左移2位就是20,而左移3位就是40超过了24,因此第一部分商为22=4.
对余数4再进行分析,发现5不需要移位就比4大,因此第二部分商为0.
加和可得,商为4.
注意:先提升为long long int,再对结果判断是否溢出会简化很多。
class Solution { public: int divide(int dividend, int divisor) { long long int ret = divideLong(dividend, divisor); if(ret > INT_MAX || ret < INT_MIN) return INT_MAX; return ret; } long long int divideLong(long long dividend, long long divisor) { // extreme cases if(divisor == 0) return INT_MAX; if(dividend == 0) return 0; int sign = 1; if((dividend < 0) ^ (divisor < 0)) sign = -1; dividend = abs(dividend); divisor = abs(divisor); long long ret = 0; while(dividend > divisor) { int shift = 0; long long part = 1; while(dividend > (divisor << shift)) { part <<= 1; shift ++; } if(dividend == (divisor << shift)) { ret += part; break; } else {// dividend < (divisor << shift) part >>= 1; shift --; } ret += part; dividend -= (divisor << shift); } if(dividend == divisor) ret ++; return sign * ret; } };