29. divide two integers

Source: Internet
Author: User

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 shoshould 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 cocould 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.
class Solution:    def divide(self, dividend, divisor):        """        :type dividend: int        :type divisor: int        :rtype: int        """        flag = -1        if (dividend>0 and divisor>0) or (dividend<0 and divisor<0):            flag = 1        res = flag*(abs(dividend)//abs(divisor))        if res>=2**31-1:            return 2**31-1        return res

29. divide two integers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.