索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode
题目:https://oj.leetcode.com/problems/divide-two-integers/
代码(github):https://github.com/illuz/leetcode
实现除法,不能用乘、除和取模。
不能用乘、除和取模,那剩下的,还有加、减和位运算。
这里有坑,就是结果可能超 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] 029. Divide Two Integers (Medium) (C++/Python)
原文地址:http://blog.csdn.net/hcbbt/article/details/44100259