• [LeetCode] 29. Divide Two Integers(不使用乘除取模,求两数相除) ☆☆☆


    转载:https://blog.csdn.net/Lynn_Baby/article/details/80624180 

    Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

    Return the quotient after dividing dividend by divisor.

    The integer division should truncate toward zero.

    Example 1:

    Input: dividend = 10, divisor = 3
    Output: 3
    Example 2:

    Input: dividend = 7, divisor = -3
    Output: -2

    乘除取模都不让用。。那只有加减

    思路解析:

    判空,返回0
    使用long类型的变量存储division和divisor的绝对值
    如果除数小于被除数,返回0
    使用加法完成除法,注意保存加了多少倍,使用嵌套循环,外层控制division大于divisor,里层控制倍数增加一倍是否比division要小
    最后返回值的时候不要忘记注意正负号

    public int divide(int dividend, int divisor) {
            if (dividend == 0 || divisor == 0)
                return 0;
            boolean flag = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0);
            long a = Math.abs((long) dividend);// 注意要转换成long型,防止溢出
            long b = Math.abs((long) divisor);
            if (a < b)
                return 0;
            int result = 0;
            while (a >= b) {
                long tempSum = b;
                long divSum = 1;
                while (tempSum + tempSum <= a) {
                    tempSum += tempSum;
                    divSum += divSum;
                }
                a -= tempSum;
                result += divSum;
            }
            return flag == true ? -result : result;
        }
  • 相关阅读:
    redis-cluster配置
    centeros7安装docker
    redis-sentinel主从复制高可用
    redis的主从同步
    redis安全(加入密码)
    redis的持久化相关操纵
    maria(mysql)的主从复制
    nginx+uwsgi+virtualenv+supervisor部署项目
    scrapy_redis之官网列子domz
    豆瓣模拟登录(双层html)
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10302904.html
Copyright © 2020-2023  润新知