• letcode两数相除


    题解

    设未知数: Br= 125 / 3,拆进行如下拆解:

    1. Br = 125 / 3
    2. Br = (29 + 96)/3
    3. Br = 29/3 + (32 * 3) / 3
    4. Br = 29/3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
    5. Br = (5 + 24) / 3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
    6. Br = 5/3 + (8 * 3) /3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
    7. Br = (2 + 3)/3 + (2 * 2 * 2 * 3)/3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
    8. Br = 2/3 + (1 * 3)/3 + (2 * 2 * 2 * 3)/3 + (2 * 2 * 2 * 2 * 2 * 3) / 3
    9. Br = 0 + 1 + 8 + 32
    10. Br = 41

    看到这个表达式的推演,那么我们可以使用递归进行求解了

    • 为了方便计算,把除数与被除数取为负数

    • 为了判断溢出,把最小负数(int)绝对值的一半定义为静态变量:halfMax = -1073741824; 当某个数大于它时二倍必定溢出

    代码

    class Solution {
        
        /** 最小负数绝对值的一半 */
        private static final int halfMax = -1073741824;
    
        public int divide(int dividend, int divisor) {
            if (divisor == 1) return  dividend;
            if (divisor == -1) return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
            /** 两数异号:位与大于0,位或小于0  */
            boolean diff = (dividend < 0 && divisor >0) || (dividend > 0 && divisor < 0);
            /** 取为负 */
            dividend = dividend > 0 ? -dividend : dividend;
            divisor = divisor > 0 ? -divisor : divisor;
            if (dividend > divisor) return 0;
            int result = deepDivide(dividend, divisor, divisor, 1);
            return diff ?  -result : result;
        }
    
        private int deepDivide(int dividend, int divisor, int curr, int result){
            if (dividend > divisor) return 0;
            int dCurr = curr + curr;
            if (dCurr < dividend || curr < halfMax) {
                int btn = dividend - curr;
                if (btn > divisor){
                    return result;
                }
                /** 被除数与当前值差值递归 */
                return result + deepDivide(btn, divisor, divisor, 1);
            } else {
                result += result;
                if (dCurr == dividend){
                    return result;
                } else {
                    /** 被除数与当前值二倍差值递归 */
                    return deepDivide(dividend, divisor, dCurr, result);
                }
            }
        }
    }
    
  • 相关阅读:
    商量Oracle数据库的数据导入办法2
    设置sql中止跟踪
    Oracle平台运用数据库系统的规划与拓荒2
    Oracle漫衍式系统数据复制技艺1
    商议Oracle数据库的数据导入措施1
    Oracle数据库等分区表的操纵方式2
    Oracle数据库集中复制方式浅议
    Oracle分布式细碎数据复制技艺2
    根绝平静隐患 随便无视的Oracle平静成绩
    优化Oracle库表筹算的若干方法2
  • 原文地址:https://www.cnblogs.com/bokers/p/15621892.html
Copyright © 2020-2023  润新知