LeetCode | Divide Two Integers
来源:互联网 发布:网络用语大全及解释88 编辑:程序博客网 时间:2024/06/06 15:51
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
要求不使用乘法、除法或模运算实现: dividend/divisor,也就是只能用加、减或位运算。int的取值范围[-2147483648, 2147483647],即最小值的abs比最大值的abs大1,那么,除法却发生溢出的情况仅仅当:dividend=-2147483648,divisor=-1。此外要注意的是:Math.abs(-2147483648) = -2147483648,要避免这种情况public class Solution { public int divide(int dividend, int divisor) { if(divisor == 0) { return Integer.MAX_VALUE; } int result = 0; if(dividend == Integer.MIN_VALUE) { if(divisor == -1) { return Integer.MAX_VALUE; } dividend += Math.abs(divisor); //之所以这么做是为了避免下面对dividend求abs时发生溢出 result++; //经过上面一行的处理,此处result要记得加1 } if(divisor == Integer.MIN_VALUE){ //当divisor为MIN时,结果要么为1(dividend也为MIN),要么为0 return result; } boolean isNeg = (dividend^divisor)>>>31 ==1; //用xor,并右移31位高位补0的方法来判断结果的正负 //乘法可能会溢出,且题目不让用,此外位运算效率高 dividend = Math.abs(dividend); divisor = Math.abs(divisor); //经过上面的处理和判断,此处的abs运算肯定不会溢出 //经过上面的处理,问题变成两个正整数的除,且不会溢出 //思路是任一个数可以表示成以2的幂为底的一组基的线性组合,num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n //且位运算中,左移相当于*2,右移相当于/2 //先让除数左移直到大于被除数之前得到一个最大的基,然后接下来每次尝试减去这个基, //如果可以则结果增加加2^k,然后基继续右移迭代,直到基为0为止 int digit = 0; //标记移了多少位 while(divisor <= (dividend>>1)) { divisor <<= 1; digit++; } while(digit>=0) { if(dividend >= divisor){ result += 1<<digit; dividend -= divisor; } divisor >>= 1; digit--; } return isNeg ? -result : result; }}
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
- Java的一些概念整理
- zebra/quagga ospf and unh test section 3
- HDU---1114-Piggy-Bank (背包)
- LoaderManager使用详解(四)---实例:AppListLoader
- cordova学习三:config.xml文件配置
- LeetCode | Divide Two Integers
- zebra/quagga ospf and unh test section 4
- 30.改变学生结构体数组中的值
- 黑马程序员JAVA笔记4--继承
- jquery 使用$.ajax post方法提交数据
- 一些PHP性能的优化
- 黑马day06 其他重要标签
- android目录结构
- office2007在win7 64上空闲状态cpu消耗7-15%的解决方法