LeetCode - Divide Two Integers
2013-12-07 05:00
302 查看
Divide Two Integers
2013.12.7 04:52
Divide two integers without using multiplication, division and mod operator.
Solution:
Another bit-manipulation problem, integer division. Normally if we calculate x / y (x, y > 0), we'll subtract y from x until y < x. This operation can be accelerated if we subtract x << (..., 2, 1, 0) from y, until x < y, using only log2(x) time.
Time complexity is O(log(dividend) - log(divisor)), space complexity is O(1).
Accepted code:
2013.12.7 04:52
Divide two integers without using multiplication, division and mod operator.
Solution:
Another bit-manipulation problem, integer division. Normally if we calculate x / y (x, y > 0), we'll subtract y from x until y < x. This operation can be accelerated if we subtract x << (..., 2, 1, 0) from y, until x < y, using only log2(x) time.
Time complexity is O(log(dividend) - log(divisor)), space complexity is O(1).
Accepted code:
// 2RE, 2WA, 1AC class Solution { public: int divide(int dividend, int divisor) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. // 2RE here, -2147483648 is a tricky case long long int div1, div2; int s1, s2; long long int base; // 1WA here, $r overflows, must be long long int long long int res, r; s1 = sign(dividend); s2 = sign(divisor); if(s1 * s2 == 0){ return 0; } div1 = dividend > 0 ? dividend : -(long long int)dividend; div2 = divisor > 0 ? divisor : -(long long int)divisor; base = div2; r = 1; while(base <= div1){ base <<= 1; r <<= 1; } res = 0; while(r > 0){ if(div1 >= base){ div1 -= base; res += r; } base >>= 1; r >>= 1; } if(s1 < 0){ res = -res; } if(s2 < 0){ res = -res; } // 1WA here, forgot to multiply sign variables return res; } private: int sign(int x){ if(x > 0){ return 1; }else if(x < 0){ return -1; }else{ return 0; } } };
相关文章推荐
- 【LeetCode 29】Divide Two Integers
- 【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers(两个整数相除)】
- [LeetCode]29. Divide Two Integers
- LeetCode之Divide Two Integers
- [LeetCode]Divide Two Integers
- Leetcode 29. Divide Two Integers
- 【leetcode-29】Divide Two Integers(C)
- #leetcode#Divide Two Integers
- [leetcode] 29. Divide Two Integers
- LeetCode题解——Divide Two Integers
- Java for LeetCode 029 Divide Two Integers
- [LeetCode]Divide Two Integers
- Divide Two Integers leetcode java
- python写算法题:leetcode: 29. Divide Two Integers
- LeetCode029 Divide Two Integers
- leetcode 29. Divide Two Integers
- leetcode 29: Divide Two Integers
- Leetcode29 Divide Two Integers
- LeetCode 29. Divide Two Integers
- 【Leetcode】之Divide Two Integers