[LeetCode] 029. Divide Two Integers (Medium) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode

029. Divide Two Integers (Medium)

链接

题目:https://oj.leetcode.com/problems/divide-two-integers/
代码(github):https://github.com/illuz/leetcode

题意

实现除法,不能用乘、除和取模。

分析

不能用乘、除和取模,那剩下的,还有加、减和位运算。

  1. 会想到的就是一次次去减,不过这样会超时。
  2. 在 1 的基础上优化下,跟快速幂一样,每次把除数翻倍(用位运算即可)。

这里有坑,就是结果可能超 int 范围,所以最好用 long long 处理,之后再转 int。

代码

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 sign:
            ret = -ret
        return min(max(-2147483648, ret), 2147483647)


你可能感兴趣的:(LeetCode,C++,算法,python)