当前位置:网站首页>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;
}
}
边栏推荐
- 自動裝箱與拆箱了解嗎?原理是什麼?
- openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
- (2) New methods in the interface
- Adaptiveavgpool1d internal implementation
- LeetCode - 919. 完全二叉树插入器 (数组)
- Synchronization control between tasks
- 01仿B站项目业务架构
- LeetCode - 673. Number of longest increasing subsequences
- YOLO_ V1 summary
- QT setting suspension button
猜你喜欢
It is difficult to quantify the extent to which a single-chip computer can find a job
Crash工具基本使用及实战分享
Cases of OpenCV image enhancement
LeetCode 面试题 17.20. 连续中值(大顶堆+小顶堆)
Working mode of 80C51 Serial Port
Yocto technology sharing phase IV: customize and add software package support
Dictionary tree prefix tree trie
Gpiof6, 7, 8 configuration
Leetcode - 933 number of recent requests
Opencv histogram equalization
随机推荐
Leetcode interview question 17.20 Continuous median (large top pile + small top pile)
Notes on C language learning of migrant workers majoring in electronic information engineering
CV learning notes ransca & image similarity comparison hash
QT is a method of batch modifying the style of a certain type of control after naming the control
Modelcheckpoint auto save model
2021-11-11 standard thread library
My notes on intelligent charging pile development (II): overview of system hardware circuit design
Leetcode 300 最长上升子序列
(2) New methods in the interface
QT self drawing button with bubbles
Screen display of charging pile design -- led driver ta6932
01仿B站项目业务架构
Dynamic layout management
LeetCode - 706 设计哈希映射(设计) *
The underlying principle of vector
One click generate traffic password (exaggerated advertisement title)
Leetcode 300 longest ascending subsequence
Wireshark use
My notes on the development of intelligent charging pile (III): overview of the overall design of the system software
On the problem of reference assignment to reference