首页 技术 正文
技术 2022年11月23日
0 收藏 636 点赞 3,409 浏览 719 个字

leetcode面试准备:Divide Two Integers

1 题目

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

接口: public int divide(int dividend, int divisor)

2 思路

题意

不用乘、除、mod 做一个除法运算。

直接用除数去一个一个加,直到被除数被超过的话,会超时。

解决办法:每次将被除数增加1倍,同时将count也增加一倍,如果超过了被除数,那么用被除数减去当前和再继续本操作。

复杂度: O(n)

3 代码

public int divide(int dividend, int divisor) {
// 处理负数
int xor = dividend ^ divisor;
int signal = xor >= 0 ? 1 : -1;
// 正常逻辑
long count = 0;
long num = Math.abs((long) dividend), div = Math.abs((long) divisor);
long tmp = div;
while (num >= tmp) {
long countTmp = 1;
while (num >= tmp) {
tmp = tmp << 1;
countTmp = countTmp << 1;
}
count += countTmp >> 1;
tmp = tmp >> 1;
num = num - tmp;
tmp = div;
}
// 处理溢出的特殊用例{-2147483648, -1}
long res = count * signal;
return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)res;
}

4 总结

数学思维,考智商。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860