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


    29.两数相除

    image-20231122200758228

    思路:

    image-20231122200838443

    image-20231122200858736

    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;
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
  • 相关阅读:
    CAD二次开发LineSegment2d
    【小程序】统计字符
    SpringMVC入门的注解、参数传递、返回值和页面跳转---超详细教学
    opencv 暴力特征匹配+FLANN特征匹配
    Mysql中完整性约束语法问题
    day38
    数据库实验:SQL的数据更新
    OrCAD原理图关联Allegro PCB交互设计设置的方法
    代码随想录二刷 | 数组 | 总结篇
    异步事件实现原理
  • 原文地址:https://blog.csdn.net/qq_46656857/article/details/134561647