码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Divide Two Integers

时间:2016-03-20 14:27:14      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return 2147483647

 

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
        
        if(divisor == 0)
            return 2147483647;
        
        if(dividend == 0)
            return 0;
        
        if(divisor == 1)
            return dividend;
        
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }
        
        boolean neg = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0);
        
        long num = Math.abs((long) dividend);
        long den = Math.abs((long) divisor);
        
        long result = 0;
        
        while(num >= den){
            int shift = 0;
            
            while(num >= (den << shift))
                shift++;
            
            num -= den<<(shift - 1);
            
            result += 1 << (shift - 1);
        }
        if(neg){
            if(result > Math.abs((long) Integer.MIN_VALUE))
                return 2147483647;
            else    
                return (int) (-result);
        }
        else{
            if(result > (long) Integer.MAX_VALUE)
                return 2147483647;
            else
                return (int) result;
        }
    }
}

 

lintcode-medium-Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5297507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!