LeetCode-29. Divide Two Integers
2017-02-19 15:37
357 查看
一、问题描述
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
二、问题分析
写一个算法不使用乘法、除法和取余运算来实现除法运算。首先想到的是被除数不断的减去除数,并不断的判断新的被除数和除数的大小来实现,但是如果被除数等于Integer.MAX_VALUE,而除数等于1时将会超时。简单点的实现方法就是移位操作。
例如,计算20/3,发现20-3<<3<0,计算新的被除数为20-3<<2=8,再次计算8/3,发现8-3<<2<0,计算新的被除数为8-3<<1=2,已经小于除数,结束。计算商为2^2+2^1=6。
注意:1.溢出问题,如Integer.MIN_VALUE/(-1),会超出int的范围,需要处理。
2.除数为0的情况,被除数为0的情况
三、代码
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor==0)
return Integer.MAX_VALUE;
if(dividend==0)
return 0;
long m=Math.abs((long)dividend);
long n=Math.abs((long)divisor);
long result=0;
while(m>=n){
int i=0;
while(m-(n<<i)>=0){
i++;
}
result+=Math.pow(2,i-1);
m-=n<<(i-1);
}
if((dividend>0 && divisor<0)||(dividend<0 && divisor>0))
result*=(-1);
if(result>Integer.MAX_VALUE||result<Integer.MIN_VALUE)
return Integer.MAX_VALUE;
return (int)result;
}
}
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
二、问题分析
写一个算法不使用乘法、除法和取余运算来实现除法运算。首先想到的是被除数不断的减去除数,并不断的判断新的被除数和除数的大小来实现,但是如果被除数等于Integer.MAX_VALUE,而除数等于1时将会超时。简单点的实现方法就是移位操作。
例如,计算20/3,发现20-3<<3<0,计算新的被除数为20-3<<2=8,再次计算8/3,发现8-3<<2<0,计算新的被除数为8-3<<1=2,已经小于除数,结束。计算商为2^2+2^1=6。
注意:1.溢出问题,如Integer.MIN_VALUE/(-1),会超出int的范围,需要处理。
2.除数为0的情况,被除数为0的情况
三、代码
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor==0)
return Integer.MAX_VALUE;
if(dividend==0)
return 0;
long m=Math.abs((long)dividend);
long n=Math.abs((long)divisor);
long result=0;
while(m>=n){
int i=0;
while(m-(n<<i)>=0){
i++;
}
result+=Math.pow(2,i-1);
m-=n<<(i-1);
}
if((dividend>0 && divisor<0)||(dividend<0 && divisor>0))
result*=(-1);
if(result>Integer.MAX_VALUE||result<Integer.MIN_VALUE)
return Integer.MAX_VALUE;
return (int)result;
}
}
PS:明天就开学了,希望开学以后也能坚持每天刷一刷!
相关文章推荐
- [LeetCode]29. Divide Two Integers
- [Leetcode] 29. Divide Two Integers
- 【leetcode-29】Divide Two Integers(C)
- [LeetCode-Java]29. Divide Two Integers
- leetcode: 29. Divide Two Integers [✗]
- [Leetcode] 29. Divide Two Integers 解题报告
- LeetCode 29 Divide Two Integers (C,C++,Java,Python)
- LeetCode 29. Divide Two Integers
- Leetcode 29 Divide Two Integers 位操作的巧妙运用
- [LeetCode] 29. Divide Two Integers ☆☆
- Leetcode 29 Divide Two Integers
- LeetCode --- 29. Divide Two Integers
- LeetCode(29)Divide Two Integers
- LeetCode 29 Divide Two Integers
- [Leetcode 29, medium] Divide two integers
- leetcode-29-Divide Two Integers
- [LeetCode-29] Divide Two Integers(两个整数相除,不能使用乘除取余算术符)
- LeetCode 29. Divide Two Integers
- LeetCode-29-Divide Two Integers(Numbers)-Medium
- LeetCode 29. Divide Two Integers