[LeetCode]29.Divide Two Integers

Given two integers dividend and divisor, divide two integers without
using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.ide

The integer division should truncate toward zero.this

Example 1:设计

Input: dividend = 10, divisor = 3 Output: 3 Example 2:code

Input: dividend = 7, divisor = -3 Output: -2 Note:ip

Both dividend and divisor will be 32-bit signed integers. The divisor
will never be 0. Assume we are dealing with an environment which could
only store integers within the 32-bit signed integer range: [−231,
231 − 1]. For the purpose of this problem, assume that your function
returns 231 − 1 when the division result overflows.
两个点须要注意
1.这样设计到大数运算的又不能使用乘除法的确定要使用移位符
2.注意溢出的判断,这道题就适合更改输入条件,但要注意修改了原始输入值,是否影响后面的判断it

public int divide(int dividend, int divisor) {
    int ret=0;
    boolean up=true;
    if((dividend>0 && divisor<0)||(dividend<0 && divisor>0)) up=false;
    if(divisor==Integer.MIN_VALUE){
         if(dividend==Integer.MIN_VALUE) return 1;
         else return 0;
    }
    if(dividend==Integer.MIN_VALUE) {
        if(divisor==-1) return Integer.MAX_VALUE;
        else{    
            ret++;
            dividend+=Math.abs(divisor);
        }
    }
    divisor=Math.abs(divisor);
    dividend=Math.abs(dividend);
    while(dividend>=divisor){
        int count=1;
        int power=divisor;
        while(dividend>>2>=power){
            count=count<<1;
            power=power<<1;
        }
        ret+=count;
        dividend-=power;
    }
    return up?ret:-ret;
}
相关文章
相关标签/搜索