zoukankan      html  css  js  c++  java
  • 【Leetcode】29. Divide Two Integers

    Question:

    Divide two integers without using multiplication, division and mod operator.

    If it is overflow, return MAX_INT.

    Tips:

    不使用乘除以及取余,来求两个整数的除法。如果溢出,返回Integer.MAX_VALUE;

    思路:

    首先涉及到除法,一定要保证除数不能为0.

    可以使用加法,用一个sum变量,加上divisor。这里可以采用二分查找的思想,令sum的初值为divisor,之后 sum+=sum。这样可以指数级速度找到最接近dividend,并且小于它的整数。剩下的继续这样的操作。

    代码:

    public int divide(int dividend, int divisor) {
            int sign = 1;
            //首先确定最终结果的符号
            if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
                sign = -1;
            }
            // 转换为long以免溢出
            long ldividend = Math.abs((long) dividend);
            long ldivisor = Math.abs((long) divisor);
            //分子不可等于0
            if (ldivisor == 0)
                return Integer.MAX_VALUE;
            if ((ldividend == 0) || ldividend < ldivisor)
                return 0;
            long lans = ldivid(ldividend, ldivisor);
            int ans;
            if (lans > Integer.MAX_VALUE) {
                ans = (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            } else {
                ans = (int) lans * sign;
            }
            return ans;
        }
    
        private long ldivid(long ldividend, long ldivisor) {
            if(ldividend<ldivisor)return 0;
            long sum=ldivisor;
            long ans=1;
            //二分的方式找到最接近切小于dividend的数
            while((sum+sum)<=ldividend){
                sum+=sum;
                ans+=ans;
            }
            return ans+ldivid(ldividend-sum,ldivisor);
        }
  • 相关阅读:
    邻接表
    分治
    当遇到error: stray '241' in program错误的解决方法
    cmd / msys2 添加到右菜单
    洛谷P1003 铺地毯
    【洛谷P3372】【模板】线段树 1
    【codevs1082】线段树练习 3
    【codevs1081】线段树练习 2
    【codevs1080】线段树练习1
    【洛谷P1731】生日蛋糕
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8521623.html
Copyright © 2011-2022 走看看