[lintcode medium]Divide Two Integers

Divide Two Integers

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

If it is overflow, return 2147483647

Example

Given dividend = 100 and divisor = 9, return 11.

 

public class Solution {
    /**
     * @param dividend the dividend
     * @param divisor the divisor
     * @return the result
     */
    public int divide(int dividend, int divisor) {
        // Write your code here
        int max=Integer.MAX_VALUE;
        int sign=1;
        if(divisor==0) return max;
        if(dividend==0) return 0;
        
        if(divisor<0) sign=-sign;
        if(dividend<0) sign=-sign;
        
        long tmp1=Math.abs((long)dividend);
        long tmp2=Math.abs((long)divisor);
        
        if(tmp1<tmp2) return 0;
        //if(tmp1==tmp2) {result=1;}
        
        long result=1;
        long temp=tmp2<<1;
        while(temp<tmp1)
        {
            result=result*2;
            temp=temp<<1;
        }
        
        temp=temp>>1;
        tmp1=tmp1-temp;
        while(tmp1>=tmp2)
        {
            result++;
            tmp1=tmp1-tmp2;
           
        }
        if(sign==-1)
        {
            result=-result;
            
        }
         
        if(result>max)
        {
            return max;
        }
        if(result<Integer.MIN_VALUE)
        {
            return Integer.MIN_VALUE;
        }
        return (int)result;
    }

 

posted on 2015-12-11 04:20  一心一念  阅读(166)  评论(0编辑  收藏  举报

导航