乐趣区

LeetCode29Divide-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.

The integer division should truncate toward zero.

Example 1:

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

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

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. 注意溢出的判断,这道题就适合更改输入条件,但要注意修改了原始输入值,是否影响后面的判断

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;
}
退出移动版