29. Divide Two Integers (JAVA)

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. 注意−231取绝对值后会溢出

 

class Solution {
    public int divide(int dividend, int divisor) {
        //handle overflow
        int res = 0;
        if(dividend==Integer.MIN_VALUE) 
        {
            if(divisor==-1)
                return Integer.MAX_VALUE;
            res = 1;
            dividend += Math.abs(divisor);
        }
        if(divisor==Integer.MIN_VALUE) 
            return res;
        
        //handle negative
        Boolean isNeg = false;
        if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) isNeg = true;
        dividend = Math.abs(dividend);
        divisor = Math.abs(divisor);
        
        int cnt = 0; //记录divisor左移的次数
        //找到商的最高比特位
        while(divisor <= (dividend >> 1)){ //除数与被除数/2相比,为了保证除<被除数,且防止溢出
            divisor <<= 1;
            cnt++;
        }
        
        //从最高比特位开始求出商的每一位
        while(cnt >= 0){
            if(dividend >= divisor){ //dividend > divisor说明当前比特位为1,否则为0
                dividend -= divisor;
                res += 1 << cnt;
            }
            divisor >>= 1;
            cnt--; 
        }
        
        return isNeg?-res:res;
    }
}

通过二进制位移完成乘除,每次左移一位,相当于十进制中*2;每次右移一位,相当于十进制中/2

将除数位移至小于被除数的最大值,以获取商的最高位

之后除数每右移一位,求商的后一位。用被除数-除数,如果>=0,说明该二进制位的值位1,反之则为0

上一篇:python小项目——实现简易的计算器


下一篇:linux 域名解析