[Leetcode] 029. Divide integers (Medium) (C++/python)

Source: Internet
Author: User
Tags bitwise

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

029. Divide, integers (Medium) links

Title: https://oj.leetcode.com/problems/divide-two-integers/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

To achieve division, you cannot use multiply, divide, and modulo.

Analysis

You can't use multiply, divide, and modulo, and the rest, plus, minus, and bitwise operations.

    1. Will think of is to reduce again and again, but this will time out.
    2. On the basis of 1 optimization, as fast as the power, each time the divisor doubled (with a bitwise operation can be).

There is a hole here, that is, the result may be super int range, so it is best to use a long long to process, and then go Int.

Code

C++:

Class Solution {public:    int divide (int dividend, int divisor) {ll a = Dividend >= 0? Dividend:-(LL) Dividend;ll b = Divisor >= 0? Divisor:-(LL) Divisor;ll result = 0, c = 0;bool sign = (Dividend > 0 && divisor < 0) | | (Dividend < 0 && divisor > 0); while (a >= b) {c = b;for (int i = 0; a >= C; i++, C <<= 1) {A-= C;result + = (1<<i);}} if (sign) {return Max ((LL) int_min,-result);} else {return MIN ((ll) int_max, result);}}    ;


Python:

Class solution:    # @return An integer    def divide (self, dividend, divisor): sign        = (Dividend < 0 and divisor  > 0) or (Dividend > 0 and Divisor < 0)        A, B = ABS (dividend), ABS (divisor)        ret, c = 0, 0 while        a >= B:            C = b            i = 0 while            a >= C:                A-= c                ret + = (1<<i)                i + = 1                c <<= 1        if Si GN:            ret =-ret        return min (max ( -2147483648, ret), 2147483647)


[Leetcode] 029. Divide integers (Medium) (C++/python)

Related Article

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.