Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
Test instructions
Achieve division, but do not allow multiplication, division, and modulo operations.
Ideas:
A bit less must appear very low, in fact can be used for the first time dividend minus divisor, the second time with Dividend-divisor minus 2 * divisor, the third time with dividend-3 * divisor minus 4 * divisor ... Until the reduction, then at this time obediently with dividend-(x = 1+2+4+...+2^n) * Divisor minus divisor,dividend-(x+1) * Divisor minus 2 * divisor ... Cycle, count the good number is OK. This problem has a special trick, online a lot of accept code I submit already had to pass (very curious how they did ...) ), can only be manually judged in silence.
C++:
1 classSolution {2 Public:3 intDivideintDividend,intdivisor) {4 5 if(Dividend = =0|| divisor = =0)6 return 0;7 //special judgment, exceeding maximum value should return Max_int8 if(Dividend = =-2147483648&& divisor = =-1)9 return 2147483647;Ten One Long LongA = ABS (static_cast<Long Long>(dividend)); A Long Longb = ABS (static_cast<Long Long>(divisor)); - Long LongRET =0; - the while(A >=b) - { - Long Longc =b; - + for(inti =0; a >= C; i++) - { +A-=C; AC <<=1; atRET + =1<<i; - } - } - return((dividend ^ divisor) >> to) ? (-ret): (ret); - } -};
"Leetcode 29" Divide, integers