【LeetCode刷题】-- 29.两数相除

29.两数相除

思路:

java 复制代码
class Solution {
    public int divide(int dividend, int divisor) {
        //考察被除数为最小值的情况
        if(dividend == Integer.MIN_VALUE){
            //被除数为最小值,除数是1,返回最小值
            if(divisor == 1){
                return Integer.MIN_VALUE;
            }
            //除数是-1,产生了溢出,返回最大值
            if(divisor == -1){
                return Integer.MAX_VALUE;
            }
        }
        //考察除数为最小值的情况
        if(divisor == Integer.MIN_VALUE){  //如果被除数是最小值,返回1,否则返回0
            return dividend == Integer.MIN_VALUE ? 1:0;
        }
        //考虑被除数为0的情况
        if(dividend == 0){
            return 0;
        }
        //将所有正数取相反数,将所有的数都变为负数,避免溢出的问题
        boolean rev = false;
        if(dividend > 0){
            dividend = - dividend;
            rev = !rev;
        }
        if (divisor > 0) {
            divisor = -divisor;
            rev = !rev;
        }

        List<Integer> candidates = new ArrayList<Integer>();
        candidates.add(divisor);
        int index = 0;
        //注意溢出
        //不断将Y乘以2,用加法实现,将这些结果放入数组中
        while(candidates.get(index) >= dividend - candidates.get(index)){  //这里大于是因为都是负数
            candidates.add(candidates.get(index) + candidates.get(index));
            ++index;
        }
        int ans = 0;
        //对数组进行逆向遍历,遍历到第i项,如果其大于等于X,将答案增加2^i,并将X中减去这一项的值
        for(int i = candidates.size() - 1; i>= 0;i--){
            if(candidates.get(i) >= dividend){
                ans += 1 << i;
                dividend -= candidates.get(i);
            }
        }
        return rev ? -ans : ans;
   }
}
相关推荐
聚客AI14 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v17 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工18 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农20 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了20 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo21 小时前
322:零钱兑换(三种方法)
算法
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队2 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法