当前位置:网站首页>20220605数学:两数相除
20220605数学:两数相除
2022-07-03 09:20:00 【丿SeeYouAgain】
题目描述:给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。返回被除数 dividend 除以除数 divisor 得到的商。整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2。
编码实现:
public int divide(int dividend, int divisor) {
int result = 0;
int minValue = Integer.MIN_VALUE,maxValue = Integer.MAX_VALUE;
if (dividend == 0){
return 0;
} else if(dividend == minValue && divisor == -1){
return maxValue;
} else if(dividend == minValue && divisor == 1){
return minValue;
} else if(dividend == minValue && divisor == minValue){
return 1;
} else if(divisor == minValue){
return 0;
}
boolean negative = (dividend ^ divisor) < 0;
if(dividend == minValue) {
dividend += Math.abs(divisor);
result++;
}
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
for(int i = 31; i >= 0; i--) {
if((dividend >> i) >= divisor) {
result += 1 << i;
dividend -= divisor << i;
}
}
if(result == minValue){
return maxValue;
} else{
return negative ? -result : result;
}
}
边栏推荐
- (2) New methods in the interface
- Markdown latex full quantifier and existential quantifier (for all, existential)
- Stm32 NVIC interrupt priority management
- LeetCode - 460 LFU 缓存(设计 - 哈希表+双向链表 哈希表+平衡二叉树(TreeSet))*
- Opencv notes 20 PCA
- Synchronization control between tasks
- Vscode markdown export PDF error
- About windows and layout
- Qcombox style settings
- Tensorflow built-in evaluation
猜你喜欢

Timer and counter of 51 single chip microcomputer

El table X-axis direction (horizontal) scroll bar slides to the right by default

Not many people can finally bring their interests to college graduation

The underlying principle of vector

Retinaface: single stage dense face localization in the wild

2021-10-28

Adaptiveavgpool1d internal implementation

RESNET code details

CV learning notes - camera model (Euclidean transformation and affine transformation)

LeetCode - 1670 設計前中後隊列(設計 - 兩個雙端隊列)
随机推荐
4G module board level control interface designed by charging pile
CV learning notes - clustering
Drive and control program of Dianchuan charging board for charging pile design
Interruption system of 51 single chip microcomputer
LeetCode - 1670 设计前中后队列(设计 - 两个双端队列)
Window maximum and minimum settings
2021-10-27
Serial port programming
(2)接口中新增的方法
Connect Alibaba cloud servers in the form of key pairs
Tensorflow2.0 save model
Gpiof6, 7, 8 configuration
(1) What is a lambda expression
03 fastjason solves circular references
LeetCode - 5 最长回文子串
使用密钥对的形式连接阿里云服务器
It is difficult to quantify the extent to which a single-chip computer can find a job
[keil5 debugging] warning:enumerated type mixed with other type
LeetCode - 1172 餐盘栈 (设计 - List + 小顶堆 + 栈))
QT self drawing button with bubbles