本文主要是介绍leetcode解题方案--028--Divide Two Integers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
分析
这道题还挺坑的
要考虑的点很多
比如Integer.min/-1 答案就会溢出
除数为0
被除数为0
public static int divide(int dividend, int divisor) {if (divisor == 0) {return Integer.MAX_VALUE;} else if (dividend == 0) {return 0;} else if (divisor == -1 && dividend == Integer.MIN_VALUE) {return Integer.MAX_VALUE;}int a = dividend > 0 ? 1 : -1;int b = divisor > 0 ? 1 : -1;int flag = a + b;long dividend1 = Math.abs((long) dividend);long divisor1 = Math.abs((long) divisor);int ans = 0;long divisorCopy = divisor1;while (dividend1 >= (divisor1 << 1)) {divisor1 = divisor1 << 1;}while (divisor1 >= divisorCopy) {ans = ans << 1;if (dividend1 >= divisor1) {dividend1 = dividend1 - divisor1;ans++;}divisor1 = divisor1 >> 1;}if (flag == 0) {ans = 0 - ans;}System.out.println(ans);return ans;
这篇关于leetcode解题方案--028--Divide Two Integers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!