29 divide two Integers(两数相除)

不能使用*/, int,超过的数以integer.max显示
输入 Integer.MIN_VALUE , -1
输出 Integer.MAX_VALUE

/**
    都转为负数,正数的值小
*/
class Solution {
    
    
    public int divide(int dividend, int divisor) {
    
    
        //求得两数相处的符号
        boolean isPositive = (dividend ^ divisor ) >= 0;
        //取负数
        if(dividend > 0)    dividend = opposite(dividend);
        if(divisor > 0)    divisor = opposite(divisor);
        //遍历数
        int res = 0;
        while(dividend <= divisor)
        {
    
    
            int tempDivisor = divisor;
            //用于Min的判断(8)
            int count = -1;
            //负数的相加不一定等于负数
            while(dividend<=tempDivisor && tempDivisor<0)
            {
    
    
                dividend -= tempDivisor;
                res += count;
                count += count;
                tempDivisor += tempDivisor;
            }
        }
 
        //负数那就直接返回
        //正数判断都是负数情况下的边界值;结果取反
        return isPositive ? (res == Integer.MIN_VALUE ? Integer.MAX_VALUE : opposite(res)) : res;
    }
 
    public int opposite(int x)
    {
    
    
        return ~x+1;
    }
}
 

猜你喜欢

转载自blog.csdn.net/weixin_43891573/article/details/115199546