LeetCode 29. Divide Two Integers
2017-12-07 17:00
302 查看
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
没有使用移位,而是采取了小学竖式计算的原理
If it is overflow, return MAX_INT.
没有使用移位,而是采取了小学竖式计算的原理
public int divide(int dividend, int divisor) { long dividend_long = dividend; long divisor_long = divisor; int flag = 1; if (divisor_long == 0) { return Integer.MAX_VALUE; } if (divisor_long < 0) { divisor_long = -divisor_long; flag = flag * -1; } //分子转化成字符串 String fenzi = String.valueOf(dividend_long); //处理负号 if (fenzi.charAt(0) == '-') { fenzi = fenzi.substring(1); flag = flag * -1; } //设置当前的左右游标 int left = 0; int right = 1; int length = fenzi.length(); StringBuffer sb = new StringBuffer(); int yu = 0; while (right <= length) { long now = Integer.parseInt(fenzi.substring(left,right));//将当前要计算的字符串转化为数字 now = now + yu * 10; long sum = 0; long result_now = 0; while ((sum + divisor_long) <= now) { sum += divisor_long; result_now++; } yu = (int)(now - sum); if (result_now == 0) { if (yu != 0) { if (sb.length() != 0) { sb.append(0); } left = right; right++; } else { sb.append(0); left = right; right ++; } } else { sb.append(result_now); left = right; right ++; } } if (sb.length() == 0) { return 0; } Long result = flag * Long.parseLong(sb.toString()); if (result > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (result < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } else { return result.intValue(); } }
相关文章推荐
- LeetCode 29. Divide Two Integers(除法)
- leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法
- leetcode 29. Divide Two Integers
- LeetCode 29. Divide Two Integers
- LeetCode(29)Divide Two Integers
- 【Leetcode】29. Divide Two Integers
- LeetCode 29 - Divide Two Integers
- leetcode 29. Divide Two Integers
- LeetCode 29. Divide Two Integers
- 【leetcode】29. Divide Two Integers
- Leetcode 29 Divide Two Integers 位操作的巧妙运用
- 【LeetCode 29】Divide Two Integers
- LeetCode 29 Divide Two Integers (不使用乘法,除法,求模计算两个数的除法)
- [Leetcode 87] 29 Divide Two Integers
- Leetcode 29. Divide Two Integers
- LeetCode-29-Divide Two Integers 智障题
- Leetcode -- 29. Divide Two Integers
- [LeetCode] 29. Divide Two Integers ☆☆
- Leetcode 29. Divide Two Integers
- [LeetCode]29. Divide Two Integers