Divide Two Integers LeetCode 解题报告
2017-08-22 13:43
363 查看
题目
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); }
相关文章推荐
- [LeetCode] Divide Two Integers 解题报告
- Divide Two Integers ——解题报告
- [leetcode] 29. Divide Two Integers 解题报告
- [leetcode] 371. Sum of Two Integers 解题报告
- [Leetcode] 29. Divide Two Integers 解题报告
- [leetcode] 371. Sum of Two Integers 解题报告
- [leetcode] 371. Sum of Two Integers 解题报告
- [LeetCode] Divide Two Integers 解题报告
- LeetCode解题报告—— Swap Nodes in Pairs & Divide Two Integers & Next Permutation
- [Leetcode] 600. Non-negative Integers without Consecutive Ones 解题报告
- 【LeetCode】371. Sum of Two Integers 解题报告(Python)
- Leetcode 371. Sum of Two Integers 位运算实现加法 解题报告
- LeetCode 371.Sum of Two Integers 解题报告
- LeetCode: Divide Two Integers 解题报告
- [Leetcode] 371. Sum of Two Integers 解题报告
- Leetcode 474. Ones and Zeroes 01组合 解题报告
- [LeetCode]Integer to Roman,解题报告
- 【LeetCode】88.Merge Sorted Array(easy)解题报告
- [Leetcode] 594. Longest Harmonious Subsequence 解题报告
- 【LeetCode】90.Subsets II(Medium)解题报告