Divide-IntegersTotal accepted:70841 Total submissions:448890 difficulty:medium
Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
Ideas:
dividend=a1*divisor+a2*divisor+...+an*divisor (ax 2k).
The following conditions cause an overflow:
1. Divisor is 0
2. The divisor is =int_min, the divisor is-1
Code:
Only the int type is used in the code. Pay attention to int_min=-2147483648,int_max=2147483647.
1 classSolution {2 Public:3 intDivideintDividend,intdivisor) {4 if(divisor==0|| (dividend==int_min&&divisor==-1)){5 returnInt_max;6 }7 if(divisor==1){8 returndividend;9 }Ten if(dividend==int_min) { One if(divisor&1){ A returnDivide (dividend+1, divisor); - } - Else{ the returnDivide (dividend>>1,divisor>>1); - } - } - if(divisor==int_min) { + return 0; - } + //Symbolic Judgment A BOOLSign= (dividend<0) ^ (divisor<0); at //here to prevent overflow, so here to meet Dividend!=int_min,divisor!=int_min - if(dividend<0) dividend=-dividend; - if(divisor<0) divisor=-Divisor; - intresult=0, TEMP,TEMPD; - while(dividend>=divisor) { -Tempd=Divisor; intemp=1; - //Overflow Judgment to while(int_max>>1>=tempd&÷nd>=tempd) { +tempd=tempd<<1; -temp<<=1; the } * if(dividend<tempd) { $tempd>>=1;Panax Notoginsengtemp>>=1; - } thedividend-=tempd; +result+=temp; A } the returnsign?-Result:result; + } -};
Leetcode 29. Divide integers