LeetCode -- Divide Two Integers

本文介绍了一种不使用乘除及取模操作符实现整数除法的方法。通过位运算找出除数的最大位移数,然后用被除数减去除数左移该位移数后的值,重复此过程直至剩余数小于除数。文章提供了完整的C#代码实现,并考虑了溢出等边界情况。

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

Divide Two Integers

题目描述
Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

整除两个整数,不能使用乘除,取模。

思路:
题目考的是位运算,求出除数的最大位移数max,使用被除数-1<<max,使用剩余的数继续计算。
注意特殊值的情况。

public class Solution {
    public int Divide(int dividend, int divisor) {
        if(dividend == 0){
    		return 0;
    	}
    	if(divisor == 0){
    		return dividend > 0 ? int.MaxValue : int.MinValue;
    	}
    	
    	long x1 = dividend;
    	long x2 = divisor;
    	var negtive = false;
    	if(x1 < 0){
    		x1 = -x1;
    		negtive = !negtive;
    	}
    	if(x2 < 0){
    		x2 = -x2;
    		negtive = !negtive;
    	}
    	
    	long result = 0;
    	long remain = x1;
    	while(remain >= x2)
    	{
    		var shifts = S(remain, x2);
    		remain -= x2 << shifts;
    		var v = 1<< shifts;
    		result += v;
    		//Console.WriteLine(remain + ","+ v);
        }
    	if(negtive){
    		result = -result;
    	}
    	
    	
    	if(result < 0 && (result + int.MaxValue < 0)) //// less than int.MinValue
    	{
    		return int.MaxValue;
    	}
    	
    	return (int)result;
    }
    
    private int S(long x, long y){
    	int count = -1;
    	while(x >= y){
    		x>>=1;
    		count ++;
    	}
    	return count;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值