当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

CV learning notes - clustering

Openeuler kernel technology sharing - Issue 1 - kdump basic principle, use and case introduction

Leetcode 300 最长上升子序列

yocto 技術分享第四期:自定義增加軟件包支持

LeetCode - 919. 完全二叉树插入器 (数组)

Opencv notes 17 template matching

For new students, if you have no contact with single-chip microcomputer, it is recommended to get started with 51 single-chip microcomputer

pycharm 无法引入自定义包

YOLO_ V1 summary

Opencv gray histogram, histogram specification
随机推荐
My 4G smart charging pile gateway design and development related articles
JS foundation - prototype prototype chain and macro task / micro task / event mechanism
Openeuler kernel technology sharing - Issue 1 - kdump basic principle, use and case introduction
2021-10-27
03 fastjason solves circular references
2021-01-03
Not many people can finally bring their interests to college graduation
Tensorflow2.0 save model
(1) 什么是Lambda表达式
Leetcode 300 longest ascending subsequence
Cases of OpenCV image enhancement
LeetCode - 705 设计哈希集合(设计)
01 business structure of imitation station B project
[combinatorics] combinatorial existence theorem (three combinatorial existence theorems | finite poset decomposition theorem | Ramsey theorem | existence theorem of different representative systems |
Yocto Technology Sharing Phase 4: Custom add package support
Pycharm cannot import custom package
Synchronization control between tasks
openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
01 business structure of imitation station B project
Drive and control program of Dianchuan charging board for charging pile design