Divide Two Integers LeetCode 解题报告
来源:互联网 发布:威海市网络推广专员 编辑:程序博客网 时间:2024/05/21 09:34
题目
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路
这道题是要求两个整数相除的结果,但是不能用乘除法和去余操作,但是我们可以使用加减和移位。假设现在有两个数:34和3,我们使用如下过程来计算34 / 3 ,3*2=6,小于34, 6*2 =12 ,仍然小于34,继续乘2,直到24*2 = 48 大于34,我们知道,最多到24,此时一共乘了8倍。34-24 = 10,再拿10去除以3,重复这个过程,这时还有3*3,10-3*3 = 1,小于除数3,退出除法。这个过程很像34 = 3*11+1。
这个题目的几个细节:
处理溢出
(1)、除数为0时
(2)、除数为-1且被除数为int的最小值时
(3)、int的最小值的绝对值比int最大值大1,在把数进行相除时需要把除数和被除数转为long,防止溢出。
在计算前先把除数和被除数都转为正数处理,可以方便计算。
代码
public static int divide(int dividend, int divisor) { //防止溢出 if(divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) return Integer.MAX_VALUE; //确定符号 int sign = ((dividend > 0)^(divisor > 0)) ? -1 : 1; long result = 0; //这两个数可能都是int的最小值,所以取绝对值前都要强转为long,结果也保存在long型中。 long dvd = Math.abs((long)dividend); long div = Math.abs((long)divisor); while(dvd >= div){ long tmp = div; long mul = 1; while(dvd >= (tmp << 1)){ tmp <<= 1; mul <<= 1; } dvd -= tmp; result += mul; } return (int) (sign*result); }
阅读全文
1 0
- [LeetCode] Divide Two Integers 解题报告
- [leetcode] 29. Divide Two Integers 解题报告
- [Leetcode] 29. Divide Two Integers 解题报告
- Divide Two Integers LeetCode 解题报告
- Leetcode #29 Divide Two Integers 整数相除 解题报告
- [leetcode]29. Divide Two Integers@Java解题报告
- Divide Two Integers ——解题报告
- [leetcode javascript解题]Divide Two Integers
- leetcode解题方案--028--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
- MySQL LOAD DATA INFILE 导入 CSV 格式数据
- leetcode(56). Merge Intervals
- 音乐类App原型制作分享-Qello Concerts
- neural networks deep learning Python Basics with numpy (optional) Homework
- android应用开发-从设计到实现 4-7天气详情的布局
- Divide Two Integers LeetCode 解题报告
- 好用的工具
- Alpha选股:资本资产定价模型(CAPM)
- poj 3695 Rectangles(容斥原理)
- 题目1040:Prime Number
- 源代码安全管理
- 【jzoj5329】【NOIP2017提高A组模拟8.22】【时间机器】【数据结构】【扫描线】
- SAP/ABAP: Smartforms, SSF_OPEN, SSF_CLOSE
- POJ 2417 Discrete Logging(离散对数 BSGS)