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;
}
}
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;
}
}
相关文章推荐
- thymeleaf模板的应用
- java.sql.Types,数据库字段类型,java数据类型的对应关系
- 电子报表数据稽核实践-VLOOKUP函数的妙用
- 数字四舍五入保留两位小数
- hdwiki中插件开发指南
- 使用setContentView实现跳转
- 【spring】BeanPostProcessor简介
- 网站域名知识解析:什么是动态域名
- Redis能干啥?细看11种Web应用场景
- 身份证校验
- 格式化JSON输出
- asp.net发布到IIS中出现错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
- Kafka 0.10.0
- 【斜率优化】BZOJ1096-[ZJOI2007]仓库建设
- centos7 rc.local无效
- LintCode之366 斐波那契数列
- 可能是讲解Android事件分发最好的文章
- Android Studio 实现使用AIDL的IPC通讯
- 【转】.so兼容32位和64位
- pyspark 中启动 jupyter notebook