LeetCode----29. Divide Two Integers (两数相除)
2016-09-26 15:47
399 查看
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Subscribe to see which companies asked
this question
//不能使用乘法,或者除法
//考虑除数和被除数为零的情况
Input:-2147483648-1
Output:0
Expected:2147483647
Math.abs(int)-----超出int范围,还是负数
Input:-21474836482
Output:0
Expected:-1073741824
Last executed input:-21474836482
、、\\泰勒公式
If it is overflow, return MAX_INT.
Subscribe to see which companies asked
this question
//不能使用乘法,或者除法
//考虑除数和被除数为零的情况
Input:-2147483648-1
Output:0
Expected:2147483647
Math.abs(int)-----超出int范围,还是负数
Input:-21474836482
Output:0
Expected:-1073741824
Submission Result: Time Limit Exceeded More
Details
Last executed input:-21474836482public class Solution { public int divide(int dividend, int divisor) { int sum=0; if(divisor==0){return dividend>=0?Integer.MAX_VALUE:Integer.MIN_VALUE;} if ((dividend == Integer.MIN_VALUE && divisor == -1)||(dividend == Integer.MAX_VALUE && divisor == 1)) { return Integer.MAX_VALUE; } if ((dividend == Integer.MAX_VALUE && divisor == -1)||(dividend == Integer.MIN_VALUE && divisor == 1)) { return Integer.MIN_VALUE; } if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)){ long dd=Math.abs((long)dividend);long ds=Math.abs((long)divisor); while(dd>=ds){dd=dd-ds;sum++;} return 0-sum;} else {long dd=Math.abs((long)dividend);long ds=Math.abs((long)divisor); while(dd>=ds){dd=dd-ds;sum++;} return sum;} } }
、、\\泰勒公式
public class Solution { /** * @param dividend the dividend * @param divisor the divisor * @return the result */ public int divide(int dividend, int divisor) { if (divisor == 0) { return dividend >= 0? Integer.MAX_VALUE : Integer.MIN_VALUE; } if (dividend == 0) { return 0; } if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } boolean isNegative = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0); long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); int result = 0; while(a >= b){ int shift = 0; while(a >= (b << shift)){ shift++; } a -= b << (shift - 1); result += 1 << (shift - 1); } return isNegative? -result: result; } }
相关文章推荐
- [LeetCode] 29. Divide Two Integers 两数相除
- LeetCode Divide Two Integers 不使用除号取模乘号实现两数相除
- LeetCode 29 Divide Two Integers(两个整数相除)(*)
- leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法
- leetcode 29 Divide Two Integers(整数相除)
- [Leetcode] divide two integers 两数相除
- Leetcode刷题记——29. Divide Two Integers(整数相除Divide two integers without using multiplication, division)
- [LeetCode] Divide Two Integers 两数相除
- [LeetCode-29] Divide Two Integers(两个整数相除,不能使用乘除取余算术符)
- 两数相除得最简公约数
- LeetCode 29 Divide Two Integers
- [Leetcode] 29. Divide Two Integers 解题报告
- LeetCode刷题记: 两数相加
- 【leetcode】【29】Divide Two Integers
- leetcode 29. Divide Two Integers
- LeetCode(29)-Plus One
- LeetCode | Divide Two Integers(两个数相除)
- LeetCode29: Substring with Concatenation of All Words
- python 两数相除求频率
- Divide two numbers,两数相除求商,不能用乘法,除法,取模运算