LeetCode Divide Two Integers(不使用乘、除,求模来计算商)
来源:互联网 发布:义乌淘宝摄影师招聘 编辑:程序博客网 时间:2024/05/29 11:23
题意:给出被除数,除数,求商(要求不能用乘,除,求模)
思路:用被除数减去除数,直到小于除数为止。在减的过程中能够做些优化。将除数连续左移直到大于被除数,在这个过程中可以计算是左移后的数是除数的多少倍,此时更新被除数,以及减了多少次除数。这个连续减的多少次叠加结果就是商
同时注意些细节:1、整数为int型,但是在取绝对值时用long
具体代码如下:
public class Solution{ public int divide(int dividend, int divisor) { if (0 == divisor || (dividend == Integer.MIN_VALUE && -1 == divisor)) return Integer.MAX_VALUE; int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; long divid = Math.abs((long)dividend); long divis = Math.abs((long)divisor); int res = 0; while (divid >= divis) { long mul = 1, tmp = divis; while (divid >= (tmp << 1)) { mul <<= 1; tmp <<= 1; } divid -= tmp; res += mul; } return sign > 0 ? res : -res; }}
0 0
- LeetCode Divide Two Integers(不使用乘、除,求模来计算商)
- Divide Two Integers不使用乘除法来计算两个数相除
- LeetCode Divide Two Integers 不使用除号取模乘号实现两数相除
- LeetCode (31) Divide two integers (不使用 *, /, mod 求两个数相除结果)
- Divide Two Integers 两数相除@LeetCode
- LeetCode----29. 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
- LeetCode: Divide Two Integers
- Divide Two Integers - leetcode
- Leetcode: Divide Two Integers
- 零碎知识点
- 物化视图定时刷新之trunc运用
- java的static块执行时机
- Android studio 电话号码归属地查询app简易版
- Cocos 点击事件
- LeetCode Divide Two Integers(不使用乘、除,求模来计算商)
- 数据库设计:范式与反范式
- 调优apache的性能
- Android应用Design Support Library完全使用实例
- Solr4.3.1添加Core
- 分享一下jdk重装后,javac命令可以执行,但java命令不能执行的解决方式
- 【复赛模拟试题】计数排序
- pycharm学习技巧
- 安卓列表选项生成黑线的方法