LeetCode | Divide Two Integers

题目:

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



思路:

1)考虑边界问题。
2)考虑INT_MIN与INT_MAX绝对值之间差1。
3)考虑符号。 类似
http://blog.csdn.net/lanxu_yy/article/details/11686447,将被除数以除数的1次方,2次方,2的2次方…2的n次方来分解。

代码:

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(dividend==0||divisor==0)
        {
            return 0;
        }
        
        bool positive=true;
        if(dividend>0&&divisor<0)
        {
            positive = false;
        }
        if(dividend<0&&divisor>0)
        {
            positive = false;
        }
        
        int x=dividend;
        int y=divisor;
        int result = 0;
        
        if(divisor==INT_MIN)
        {
            return dividend==INT_MIN?1:0;
        }else if(divisor<0)
        {
            y=-divisor;
        }
        
        if(dividend==INT_MIN)
        {
            x=INT_MAX-y+1;
            result+=1;
        }else if(dividend<0)
        {
            x=-dividend;
        }
        
        while(x>=y)
        {
            int sum = y;
            int count=1;
            while(sum <= x - sum)
            {
                count += count;
                sum += sum;
            };
            x -= sum;
            result+=count;
        };
        return (positive?1:-1)*result;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17592659
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞