leetcode:Divide Two Integers
来源:互联网 发布:mac安装阿里旺旺 编辑:程序博客网 时间:2024/06/05 10:49
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
需要注意的是负的最大值为-2147483648,正的最大值为2147483647;因此需要将变量设置为long类型
最开始我的想法是既然不能除,那就每次都减去被除数呗;减一次记一次数但是最后提交的时候超时了;哎,没考虑极端情况,比如除数为1,被除数为2147483647这样的;
于是考虑是不是可以逐渐递增除数,比如除数为2,那么第一次减2,第二次减4,减8,减16.。。。不够减时,再将除数除2。。。直到最后除数为2
这样就大大减小了操作次数
程序如下
public class Solution { public static int divide(int dividend, int divisor){long divid = dividend;long divs=divisor;int flag=1;double cnt = 0;if (divisor == 1)return dividend;if (divisor == -1){if (dividend == Integer.MIN_VALUE)return Integer.MAX_VALUE;elsereturn -dividend;}if (divid < 0){divid = -divid;flag=-flag;}if (divs < 0){divs = -divs;flag=-flag;}long ds = divs;double ct = 0.5;while (divid >= ds){divid = divid - ds;ct = ct * 2;cnt = cnt + ct;ds=ds*2;while (ds > divid && ds > divs){ds = ds / 2;ct = ct / 2;}if (ds == divs && ds > divid)break;}return (int) cnt * flag; }}
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
- 网站域名知识解析:什么是动态域名
- 身份证校验
- Intellij IDEA创建Maven Web项目
- java多线程并发基础
- CSS实现三角原理
- leetcode:Divide Two Integers
- Android计算函数时间戳的方法
- 实用代码块记录1
- smarty如何解决登录页面登录失败时在页面上同时显示失败的反馈信息的问题
- 用自定义的RoundImageView来实现圆形图片(可加边框)
- CSS实例教程:十步学会用CSS建站
- linux 下 的 atom编辑器安装
- hrbust 1473 教主的遗产【状压dp】
- 获取RecyclerView滑动的距离