[Leetcode] Divide Two Integers
来源:互联网 发布:postfix ubuntu 编辑:程序博客网 时间:2024/05/17 02:39
题目:
Divide two integers without using multiplication, division and mod operator.
思路:D = a0 * d * 2^n + a1 * d * 2^(n-1) + ... + an * d * 2^0,从d * 2^n开始,不断的用被除数减去这个值,同时计算ai.
最终的结果为 D / d = a0 * 2^n + a1 * 2^(n-1) + ... an * 2^0.
由于除数需要移位试探,while ((_divisor << 1) < _dividend),因此需要设置成long long型避免溢出。对于第二个循环的终止条件,进行到an * d * 2^0即可,也就是stap >= 0. 其他条件,比如_dividend >= 0等均不合适,因为可能无法除尽。
class Solution {public: inline long long abs(int a) {return a > 0 ? a : 0 - (long long)a;} inline bool is_neg(int a) {return a < 0 ? true : false;} int divide(int dividend, int divisor) { long long _dividend = abs(dividend); long long _divisor = abs(divisor); bool neg = is_neg(dividend) ^ is_neg(divisor); int step = 0; while ((_divisor << 1) < _dividend) { step++; _divisor <<= 1; } int result = 0; while (step >= 0) { while (_dividend >= _divisor) { _dividend -= _divisor; result += 1 << step; } _divisor >>= 1; step--; } return neg ? 0 - result : result; }};
总结:类似二分法,对于while (step >= 0)的大循环,因为当前循环时,被除数必然比除数的二倍要小,因此里面的小循环while (_dividend >= _divisor)在二轮内就可以执行完,因此小循环始终是O(1). 所以,复杂度取决于大循环的次数,即step的值。显然,step是log n级别的,因为根据公式可以知道,
step = n <= log (D / d),因此,复杂度为O(log n).
0 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- 【leetcode】Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode-Divide Two Integers
- LeetCode: Divide Two Integers
- Divide Two Integers - leetcode
- Leetcode: Divide Two Integers
- LeetCode:Divide Two Integers
- leetcode Divide Two Integers
- LeetCode Divide Two Integers
- LeetCode | Divide Two Integers
- Leetcode: Divide Two Integers
- Divide Two Integers -- LeetCode
- JAVA中HashMap和Hashtable区别
- RELIEF Feature Selection(RELIEF特征选择) Python实现
- java中int和string类型转换
- Java关键字final、static使用总结
- 【基础算法】位运算-找出奇特的数
- [Leetcode] Divide Two Integers
- Java基本概念:集合类(Collection)List/Set/Map... 的区别和联系
- 网上无法找到的教程,LZMA教程,欢迎大家指正
- lu 初始化设置步骤
- 发了个快递是法国
- Java程序员的JavaScript学习笔记(5——prototype和Object内置方法)
- [Leetcode] Search in Rotated Sorted Array
- PHP中的定界符 EOT
- JAVA数据类型转换