LeetCode: divideInteger

Title:

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

If it is overflow, return MAX_INT.

思路就是每次以两倍增长除数,知道即将大于被除数,然后用被除数减去,在循环。

遇到int整数问题一定要考虑到INT_MAX和INT_MIN。

 

class Solution {
public:
    int divide(int dividend, int divisor) {
        int final = 0;
        /////// overflow///////
        if (divisor == 0 || (dividend == INT_MIN && divisor == -1)){
            return INT_MAX;
        }
        int nega = 0;
        if ((dividend>0&&divisor<0) || (dividend<0&&divisor>0))
            nega = 1;
        //如果为INT_MIN则求abs为越界
        long long a = abs((long long)dividend);
        long long b = abs((long long)divisor);
        if (b > a)
            return 0;
        long long sum = 0;//后面有sum += sum防止越界
        int count = 0;
        while (a >= b)
        {
            count = 1;                //a >= b保证了最少有一个count
            sum = b;
            while (sum + sum <= a){    
                sum += sum;
                count += count; 
            }
            a -= sum;
            final += count;
        }
        if (nega)
            final = 0 - final;
        return final;
    }
};

 

posted on 2015-04-16 09:57  月下之风  阅读(236)  评论(0编辑  收藏  举报

导航