zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

    思路


       在题中明确了不能使用乘法和除法以及模运算,所以我们只能通过其他办法来进行解决。除法解决的问题就是看被除数里面有多少个除数的问题,最简单的方法就是我们可以使用减法,对被除数减去除数,然后计数加一。但是这种办法当从被除数较大时时间复杂度较高,因此我们可以对其进行改进,对被除数从除数的倍数开始减去,然后每次相减完毕之后对对除数进行加倍。这样当被除数比较大时,也能很快的相减完毕。

    解决代码


     1 class Solution(object):
     2     def divide(self, dividend, divisor):
     3         positive = (dividend < 0) is (divisor < 0)  # 被除数和除数为负数的情况进行考虑。
     4         dividend, divisor = abs(dividend), abs(divisor)    # 对其取绝对值
     5         res = 0                                     # 结果
     6         while dividend >= divisor:                 #  当被除数小于当前除数时,说明已经不能被整除了。
     7             tem, i = divisor, 1                  # 存储倍数和除数
     8             while dividend >= tem:              # 当被除数小于当前倍数除数时,终止循环
     9                 dividend -= tem                  # 被除数减去除数
    10                 res += i                         # 结果加上相应的倍数
    11                 i <<= 1                          # 除数的倍数
    12                 tem <<= 1                        # 除数翻倍
    13         if not positive:                       # 判断是否有负数
    14             res = -res
    15         return min(max(-2147483648, res), 2147483647) # 超出范围判断
  • 相关阅读:
    [HDU 2553] N皇后问题
    [ZOJ 3063] Draw Something Cheat
    [ZOJ 3609] Modular Inverse
    [ZOJ 3610] Yet Another Story of Rock-paper-scissors
    [ZOJ 3607] Lazier Salesgirl
    [ZOJ 3710] Friends
    [ZOJ 3076] Break Standard Weight
    智慧树自动刷课代码
    Attention
    sizeof总结
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10664470.html
Copyright © 2011-2022 走看看