Divide Two Integers

题目描述:

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

If it is overflow, return MAX_INT.

不能用*,/,%来实现除法。

最原始的就是用减法实现,但是会超时,比如123456789/1会除123456789次。

那么还可以用位运算符<<,>>来运算

例如16/3

3*2*2*2=24

16-12=4

4-3=1结束运算

代码如下:

public class Solution {
    public int divide(int dividend, int divisor) {  
        int sign = 1;  
        if(dividend>0^divisor>0) sign = -sign;   
        long temp = Math.abs((long)dividend);  
        long temp2 = Math.abs((long)divisor);  
        long c = 1;  
        while(temp>temp2){  
            temp2 = temp2<<1;  
            c = c<<1;  
        }
        long res = 0;  
        while(temp>=Math.abs((long)divisor)){  
            if(temp>=temp2){  
                temp-=temp2;  
                res+=c;  
            }  
            temp2 = temp2>>1;  
            c=c>>1;  
        }  
        if(sign>0) return (int)(res>Integer.MAX_VALUE?Integer.MAX_VALUE:res);  
        else return (int)(-res>Integer.MAX_VALUE?Integer.MAX_VALUE:-res); 
    } 
}



你可能感兴趣的:(java,Math,LeetCode)