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

Source: Internet
Author: User
Tags abs

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode 029. Divide two integers (Medium) link :

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

To achieve division, you cannot use multiplication, division, and modulo. Analysis :

You can't use multiplication, divide and take modulo, the rest, plus, minus and bitwise operations. The idea is to subtract from time to time, but it will time out. On the basis of 1 optimization, like a fast power, the divisor doubled each time (using bit operation can).

There's a hole here, which means the result may be a range of int, so it's best to use long long, and then go Int. code :

C++:

Class Solution {public
:
    int divide (int dividend, int divisor) {
		ll a = Dividend >= 0? Dividend:-(LL) Div Idend;
		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), or
		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)


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.