Divide Two Integers题解以及类似题目的总结
来源:互联网 发布:桌面美化软件 编辑:程序博客网 时间:2024/06/03 23:25
29. Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路很简单,既然不能用乘除法,自然是用加减法了来代替。
瓶颈也很显而易见,按线性加减发会超时。
这个题目有两个思路,先说第一个。
假设现在我们是算x / y,那么考虑x > 2^n * y,求出这个最大的2^n,然后将x减去2^n * y,然后继续求新的2^n,直到x<y,最后将历次2^n加起来就是答案了。有没有种二进制的意思。
public class Solution { public int divide(int dividend, int divisor) { long result = 0; int flag = 1; if (dividend < 0) flag = -flag; if (divisor < 0) flag = -flag; long x = Math.abs((long)dividend); long y = Math.abs((long)divisor); while (x>=y) { long temp = y; long c = 1; while (temp <= x) { temp <<= 1; c <<= 1; } result += (c>>1); x -= (temp>>1); } if (result*(long)flag > Integer.MAX_VALUE || result*(long)flag < Integer.MIN_VALUE) return Integer.MAX_VALUE; else return (int)(result*(long)flag); }}
第二个思路很简单,就是预处理,比如我们还是算x / y,我们怕的不就是当出现2000000000 / 1这种情况出现时会超时吗,那我们先预处理y的倍数,我先用加法把y的100000倍预先算出来,存位m,然后用x一次次去减m就行了,当最后x < m的时候,再对剩下的x作 x / y,结果就是剩下的x /y + 100000*m。
用这个方法来个实战。
50. Pow(x, n)
Implement pow(x, n).
class Solution {public: double myPow(double x, int n) { double result = 1; if (n >= 0) { double temp = 1; for (int i=0; i<10000; i++) temp *= x; while (n-10000 > 0) { result *= temp; n -= 10000; } for (int i=0; i<n; i++) result *= x; return result; } else { long m = n; m = -m; double temp = 1; for (int i=0; i<10000; i++) temp *= x; while (m-10000 > 0) { result *= temp; m -= 10000; } for (int i=0; i<m; i++) result *= x; return 1/result; } }};
本菜正在刷LeetCode,写过的代码都放到了https://github.com/lcxywfe/LeetCode,欢迎各犇交流~
0 0
- Divide Two Integers题解以及类似题目的总结
- LeetCode的一个题目 Divide Two Integers
- LeetCode题解:Divide Two Integers
- [题解][LeetCode][Divide Two Integers]
- LeetCode题解:Divide Two Integers
- LeetCode题解——Divide Two Integers
- LeetCode 题解(177): Divide Two Integers
- leetcode题解-29. Divide Two Integers
- Middle-题目127:29. Divide Two Integers
- leecode 解题总结:29 Divide Two Integers
- Divide Two Integers我的解法
- Divide Two Integers 的两种解法
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- maven项目中 使用mybatis 出现 Invalid bound statement (not found) 错误原因之一
- bio nio aio的区别
- Form action defaulting to 'action' attribute's literal value.
- 标准文件对话框扩展
- Linux应用随笔(六)MTP访问安卓手机内部存储
- Divide Two Integers题解以及类似题目的总结
- Error:Execution failed for task ':app:transformClassesWithDexForDebug'
- linux下解压命令大全
- Android 如何监听返回键,弹出一个退出对话框
- matlab GUI界面实现单选按钮(radiobutton)
- 使用EditText出现java.lang.StackOverflowError报错
- python 画三维图像 曲面图和散点图
- 第7周 项目5-模拟看病模拟
- QSound一句代码播放简单的音效