首页 > 代码库 > Divide Two Integers

Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

思路:取被除数和除数的绝对值求解即可。不过,需要考虑特殊情况:INT_MIN取绝对值仍然是INT_MIN。

 1 class Solution { 2 public: 3     int divide( int dividend, int divisor ) { 4         if( divisor == 0 ) { return -1; } 5         if( dividend == 0 ) { return 0; } 6         if( divisor == INT_MIN ) { return dividend == INT_MIN; } 7         int ret = 0, sign = dividend > 0; 8         if( divisor < 0 ) { sign = !sign; } 9         if( dividend == INT_MIN ) {10             dividend += abs( divisor );11             ret = 1;12         }13         dividend = abs( dividend );14         divisor = abs( divisor );15         int num = 0;16         while( dividend - (divisor<<num) >= (divisor<<num) ) { ++num; }17         while( num >= 0 ) {18             if( dividend >= (divisor<<num) ) {19                 dividend -= (divisor<<num);20                 ret += (1<<num);21             }22             --num;23         }24         return sign ? ret : -ret;25     }26 };

 

Divide Two Integers