一 题目
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3 Output: 3
Example 2:
Input: dividend = 7, divisor = -3 Output: -2
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
二 分析
给定两个整数,要求不用乘除法和取模运算,计算出a/b的值,当结果越界的时候输出INT最大值。
我想那就替换下,用倍数来实现吧。
public static int divide(int dividend, int divisor) {
if(divisor == -1){
if(dividend== Integer.MIN_VALUE){
return Integer.MAX_VALUE;
}
return -dividend;
}
if(dividend ==0){
return 0;
}
int d1 = dividend>0?dividend:-dividend;
int d2 = divisor>0?divisor:-divisor;
//求倍数
int tmp = 0;
int c =0;
while(tmp<=d1 ){
tmp = tmp+d2;
if(tmp<=d1){
c++;
}
}
return (dividend>0)^(divisor>0)?-c :c;
}
遇到问题就是大数在2147483647 除以1,2这种小数时,迭代求和周期太长,出现了TLE错误。
想起来之前说的遇到指数增长问题,如何寻找迭代的步长呢?一个数没左移1位,就是乘以2的指数。
以3为例,就是3*2^0.=3,3*2^1=6;3*2^2=12,3*2^3=24;3*2^4=48;3*2^5=96;......
int类型范围就是-2^31---2^31-1; 所以最大32位就可以覆盖。不用想之前那种每次只加除数。再将被除数减去这个商乘以除数,一直到被除数剩下的小于除数,就是所谓的余数为止,这样就快了很多。
public static int divide(int dividend, int divisor) {
if(divisor == -1){
if(dividend== Integer.MIN_VALUE){
return Integer.MAX_VALUE;
}
return -dividend;
}
if(dividend ==0){
return 0;
}
long d1 =Math.abs((long)dividend);
long d2 = Math.abs((long)divisor);
//求倍数
int c =0;
while(d2<=d1 ){
int b=0;
while((d2<<b) <=d1){
b++;
}
b--;
c= c+(1<<b);
d1 =d1-(d2<<b);
}
return (dividend>0)^(divisor>0)?-c :c;
}
我在提交的时候,遇到的一个问题就是abs的问题,遇到边界值,-2147483648 就是Integer.MIN_VALUE ,如果不用long,math.abs 不起作用。还需要额外判断。
Runtime: 1 ms, faster than 100.00% of Java online submissions for Divide Two Integers.
Memory Usage: 33.5 MB, less than 6.06% of Java online submissions forDivide Two Integers.
效果还是不错的。