【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;
   }
}
相关推荐
ysy164806723928 分钟前
03算法学习_977、有序数组的平方
学习·算法
codists1 小时前
《算法导论(第4版)》阅读笔记:p83-p85
算法
Tiny番茄1 小时前
归一化函数 & 激活函数
人工智能·算法·机器学习
jz_ddk1 小时前
[学习] RTKLib详解:rtcm2.c、rtcm3.c、rtcm3e与rtcmn.c
c语言·学习·算法
小学生的信奥之路2 小时前
力扣1991:找到数组的中间位置(前缀和)
数据结构·算法·leetcode·前缀和·数组
এ᭄画画的北北2 小时前
力扣-102.二叉树的层序遍历
数据结构·算法·leetcode
ccLianLian2 小时前
数据结构·字典树
数据结构·算法
JeffersonZU4 小时前
【数据结构】1-4算法的空间复杂度
c语言·数据结构·算法
L_cl4 小时前
【Python 算法零基础 4.排序 ① 选择排序】
数据结构·算法·排序算法
山北雨夜漫步5 小时前
机器学习 Day18 Support Vector Machine ——最优美的机器学习算法
人工智能·算法·机器学习