Leetcode-29. Divide Two Integers

题目描述:

  

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

If it is overflow, return MAX_INT.

 

思路:

  不能用除法,只能想到减法,但是结果最大可能是-INT_MIN,所以容易超时。所以用二进制进位解决;

dividend=2^(n)*divisor+2^(n-1)*divisor+...+2^0*divisor;

 

Code:

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(dividend==INT_MIN)
        {
            if(divisor==-1)
            return INT_MAX;
            if(divisor==1)
            return INT_MIN;
        }
        
        long long x = abs((long) dividend);  
        long long y = abs((long) divisor); 
        
        long long result=0;
        long long temp=y;
        while(x>=y)
        {
            temp=y;
            for(int i=0;x>=temp;i++)
            {
                x-=temp;
                result+=(1<<i);
                temp=temp<<1; //注意,此处若写成temp<<1是错误的,temp<<1不会改变temp本身的值
            }
        }
        return ((dividend^divisor)>>31)? (int)(-result):(int)(result);
    }
};

 

 
posted @ 2016-08-27 22:34  Pacific-hong  阅读(90)  评论(0编辑  收藏  举报