LeetCode Divide Two Integers 不使用除号取模乘号实现两数相除
2013-11-27 17:13
661 查看
Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
不使用乘法,除法和模操作实现除法运算。
思路就是用被除数减去除数,减尽为止,如下面程序。
不过很可惜,上面的程序是无法通过的,因为需要优化一下。上面的程序是基本思想,所以,先要知道这个程序。
下面是两个优化的程序,都可以AC。
2014-1-25 update
Divide two integers without using multiplication, division and mod operator.
不使用乘法,除法和模操作实现除法运算。
思路就是用被除数减去除数,减尽为止,如下面程序。
int divide(int dividend, int divisor) { //这里的dividend如果不加long long或者加double, 就会当是INT_MIN的时候溢出 long long a = abs((long long)dividend); long long b = abs((long long)divisor); int result = 0; while (a >= b) { a -= b; result++; } return (dividend>>31 ^ divisor>>31)? -result:result; }
不过很可惜,上面的程序是无法通过的,因为需要优化一下。上面的程序是基本思想,所以,先要知道这个程序。
下面是两个优化的程序,都可以AC。
int divide2(int dividend, int divisor) { //这里的dividend如果不加long long或者加double, 就会当是INT_MIN的时候溢出 long long a = abs((long long)dividend); long long b = abs((long long)divisor); int result = 0; while (a >= b) { int count = 0; while (a >= b<<(count+1)) count++; a -= b<<count; result += 1<<count; } return (dividend>>31 ^ divisor>>31)? -result:result; } int divide3(int dividend, int divisor) { long long a = abs((long long)dividend); long long b = abs((long long)divisor); int result = 0; while (a >= b) { int count = 0; while (a >= b<<count) { result += 1<<count; a -= b<<count; count++; } } return (dividend > 0) ^ (divisor > 0) ? -result : result; }
2014-1-25 update
//忘记考虑溢出问题!!!How can I forget???!!! int divide(int dividend, int divisor) { long long a = dividend; long long b = divisor; a = abs(a); b = abs(b); int res = 0; while (a>=b) { long long t = b; for (int i = 1; a >= t; i <<= 1, t <<= 1) { a -= t; res += i; } } return ((dividend<0)^(divisor<0))? -res:res; }
相关文章推荐
- [LeetCode-29] Divide Two Integers(两个整数相除,不能使用乘除取余算术符)
- [LeetCode] 29. Divide Two Integers 两数相除
- 【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers(两个整数相除)】
- [Leetcode] divide two integers 两数相除
- [LeetCode] Divide Two Integers 两数相除
- LeetCode 29 Divide Two Integers (不使用乘法,除法,求模计算两个数的除法)
- LeetCode OJ:Divide Two Integers(两数相除)
- leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法
- LeetCode Divide Two Integers(不使用乘、除,求模来计算商)
- 【Leetcode】 - Divide Two Integers 位运算实现整数除法
- Leetcode刷题记——29. Divide Two Integers(整数相除Divide two integers without using multiplication, division)
- LeetCode 29 Divide Two Integers(两个整数相除)(*)
- [LintCode] Divide Two Integers 两数相除
- LeetCode之操作两个数相除DivideTwoIntegers
- leetcode 29 Divide Two Integers(整数相除)
- (LeetCode) Divide Two Integers (Java)思路讲解及实现
- LeetCode (31) Divide two integers (不使用 *, /, mod 求两个数相除结果)
- LeetCode | Divide Two Integers(两个数相除)
- leetcode:Divide Two Integers
- leetcode Divide Two Integers