您的位置:首页 > 其它

leetcode:Divide Two Integers

2016-07-06 13:41 417 查看
Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

需要注意的是负的最大值为-2147483648,正的最大值为2147483647;因此需要将变量设置为long类型

最开始我的想法是既然不能除,那就每次都减去被除数呗;减一次记一次数但是最后提交的时候超时了;哎,没考虑极端情况,比如除数为1,被除数为2147483647这样的;

于是考虑是不是可以逐渐递增除数,比如除数为2,那么第一次减2,第二次减4,减8,减16.。。。不够减时,再将除数除2。。。直到最后除数为2

这样就大大减小了操作次数

程序如下
public class Solution {
public static int divide(int dividend, int divisor)
{
long divid = dividend;
long divs=divisor;
int flag=1;
double cnt = 0;
if (divisor == 1)
return dividend;
if (divisor == -1)
{
if (dividend == Integer.MIN_VALUE)
return Integer.MAX_VALUE;
else
return -dividend;
}
if (divid < 0)
{
divid = -divid;
flag=-flag;
}
if (divs < 0)
{
divs = -divs;
flag=-flag;
}
long ds = divs;
double ct = 0.5;
while (divid >= ds)
{
divid = divid - ds;
ct = ct * 2;
cnt = cnt + ct;
ds=ds*2;
while (ds > divid && ds > divs)
{
ds = ds / 2;
ct = ct / 2;
}
if (ds == divs && ds > divid)
break;
}
return (int) cnt * flag;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: