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

    这题

    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

    Note:

    • Both dividend and divisor will be 32-bit signed integers.
    • The divisor will never be 0.
    • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows.

    这题提示不能用乘法,除法,取余,所以可以用的是可以用加法,减法, >>1, <<1的位运算。

    因为只能用位运算代替乘除,所以我们用2的幂次来组成结果。从最大头的部分开始,之后减去后,依次求解。这题另外提示可能会overflow所以要处理边界问题,能出现2^ 31的情况只有被除数为:

    -2^31,除数为-1的情况(The divisor will never be 0)。代码如下:

    class Solution(object):
        def divide(self, dividend, divisor):
            """
            :type dividend: int
            :type divisor: int
            :rtype: int
            """
            int_max = 2**31-1
            int_min = -2**31
            if divisor == 0 or (dividend == int_min and divisor == -1):
                return int_max
            sign = 1 if ((dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0)) else -1 
            
            divid = abs(dividend)
            divis = abs(divisor)
            
            res = 0
    #注意这里要保存为相等,防止开始被除数和除数相等的情况
    while divid >= divis: cur = divis cnt = 1
    #处理整除的情况 while cur <= divid: cur = cur << 1 cnt = cnt << 1 res += cnt >> 1 divid -= cur >> 1 if sign > 0: return res else: return -res

    注意代码对整除,被除数和除数相等的情况要做下处理,所以要保存等号

  • 相关阅读:
    【1】maven来管理我的SSM项目
    mybatis从数据库中取到的date格式不是yyyy-MM-dd HH:mm:ss
    hadoop的webUI查看Live Nodes为1
    CentOS6.8系统下,ecipse下进行编辑操作,意外退出
    【5】namenode启动过程
    电脑意外重启,导致虚拟机启动失败
    第3章 路由和数据传递
    第2章 基于三层架构搭建MVC系统
    第1章 进入ASP.NET MVC世界
    第13章 集合
  • 原文地址:https://www.cnblogs.com/sherylwang/p/9736712.html
Copyright © 2011-2022 走看看