本文主要是介绍leetcode -- 29. Divide Two Integers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
题目难度:Medium
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
- Input: dividend = 10, divisor = 3
- Output: 3
Example 2:
-
Input: dividend = 7, divisor = -3
-
Output: -2
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
AC代码
leetcode 上面优秀的代码
class Solution {public int divide(int dividend, int divisor) {int sign=1;if((divisor<0 && dividend>0) || (divisor>0 && dividend<0)) sign=-1;long dd=Math.abs((long)dividend);long dr=Math.abs((long)divisor);long q=helper(dd,dr);if(q>Integer.MAX_VALUE){if(sign==1) return Integer.MAX_VALUE;else return Integer.MIN_VALUE;}return (int)q*(sign);}private long helper(long dd,long dr){if(dd<dr) return 0;long m=1,sum=dr;while((sum+sum)<=dd){sum+=sum;m+=m;}return m+helper(dd-sum,dr);}
}
这篇关于leetcode -- 29. Divide Two Integers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!