Leetcode: Divide Two Integers

本文介绍了一种不使用乘法、除法和取模运算符来实现整数除法的方法。仅利用加法、减法及位操作实现了算法,并考虑了溢出情况。通过不断左移除数直至其大于被除数,进行位操作计算商。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Only plus, minus, and bit manipulation is allowed to solve this question. Left shifting a integer by a bit is actually doubling that integer. So keep left shifting the divisor until the result is larger than the dividend. Calculate the dividend minus the last result after shifting the divisor, and use the minus result to continue the bit manipulation, until it's smaller than the divisor. 

Note the possibility of overflow when calculating the absolute value of the dividend and the divisor.

public class Solution {
    public int divide(int dividend, int divisor) {
        boolean diffSign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
        long a = Math.abs((long) dividend);
        long b = Math.abs((long) divisor);
        
        int res = 0;
        while (a >= b) {
            int shift = 0;
            while ((b << shift) <= a) {
                shift++;
            }
            res += 1 << (shift - 1);
            a -= b << (shift - 1);
        }
        
        return diffSign ? -res : res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值