首页 > 代码库 > 62. Divide Two Integers

62. Divide Two Integers

Divide Two Integers

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

思路: 类同 趣味算法之数学问题:题4. 

两点需要注意: 1. 除数或被除数为最大负数时,转化为正数会溢出。2. divisor + divisor 可能会溢出。

class Solution {public:    int divide(int dividend, int divisor) {        if(divisor == 0) return INT_MAX;        bool signal = false;        bool overflow = false;        if(dividend < 0) {            signal = !signal;            if(dividend == INT_MIN) { overflow = true; dividend++; }            dividend *= -1;        }         if(divisor < 0) {            signal = !signal;            if(divisor == INT_MIN) {                if(overflow) return 1;                else return 0;            }            divisor *= -1;        }        int result = 0;        while(dividend >= divisor) {            int x(divisor);            int r(1);            while(dividend-x >= x) {                x += x;                r += r;            }            dividend -= x;            result += r;        }        if(overflow && dividend +1 == divisor) result++;        return signal ? (-result) : result;    }};

 

62. Divide Two Integers