LeetCode 29. Divide Two Integers
来源:互联网 发布:aps.net程序员招聘 编辑:程序博客网 时间:2024/05/29 09:17
Divide two integers without using multiplication, division and mod operator.
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(); } }
阅读全文
0 0
- [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 29. Divide Two Integers
- leetcode 29. Divide Two Integers
- [leetcode]29. Divide Two Integers
- leetcode 29. Divide Two Integers
- LeetCode - 29. Divide Two Integers
- c注释转换为cpp注释
- 详细了解并发-多线程关键字:volatile
- QT控件大全 九 Qnightcharts
- 了解html base标签的作用
- 小拓展 大知识
- LeetCode 29. Divide Two Integers
- 企业级界面开发工具包Essential Studio Enterprise Edition发布2017 v4丨附下载
- vim 超强配置
- 【Scikit-Learn 中文文档】监督学习:从高维观察预测输出变量
- Ansible基础元素介绍
- C++性能优化实践
- js做的一个猜数字小游戏
- centos7安装oracle12c 二
- 消息队列