[LeetCode] 415. Add Strings 解题报告
来源:互联网 发布:2016中国对外投资数据 编辑:程序博客网 时间:2024/06/17 08:05
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
这一题非常简单,记得前面有个和这个类似的题,大概是100号以前。
我的方法就是从右往左算,如果算完,直接把较长的字符串复制下来即可。另外,使用一个boolean变量控制进位就好。
我用的char型数组,主要考虑效率问题,直接String字符串是效率非常低的。
private static final char ZERO = '0';public String addStrings(String num1, String num2) {if (num1.length() == 0 || num2.length() == 0) {return num1.length() == 0 ? num1 : num2;}char[] cArr1 = num1.length() >= num2.length() ? num1.toCharArray() : num2.toCharArray();char[] cArr2 = num1.length() < num2.length() ? num1.toCharArray() : num2.toCharArray();int nCount = 0;int nMinLength = cArr2.length;int nMaxLength = cArr1.length;char[] cArrResult = new char[nMaxLength + 1];boolean bUpDigit = false;while (nCount < nMaxLength) {char c1 = cArr1[cArr1.length - nCount - 1];char c2 = nCount < nMinLength ? cArr2[cArr2.length - nCount - 1] : ZERO;int nCurrentDigit = (int) (c1 - ZERO) + (int) (c2 - ZERO);nCurrentDigit = bUpDigit ? nCurrentDigit + 1 : nCurrentDigit;bUpDigit = false;if (nCurrentDigit > 9) {bUpDigit = true;nCurrentDigit -= 10;}cArrResult[cArrResult.length - nCount - 1] = (char) (nCurrentDigit + ZERO);nCount++;}String strResult = String.valueOf(cArrResult).substring(1);return bUpDigit ? 1 + strResult : strResult;}
0 0
- [leetcode] 415. Add Strings 解题报告
- [LeetCode] 415. Add Strings 解题报告
- [Leetcode] 415. Add Strings 解题报告
- 【LeetCode】Add Strings 解题报告
- Leetcode 415. Add Strings 字符串加法 解题报告
- LeetCode 415. Add String 解题报告
- 【LeetCode】Multiply Strings 解题报告
- LeetCode-Isomorphic Strings-解题报告
- [LeetCode] Multiply Strings 解题报告
- 【LeetCode】Isomorphic Strings 解题报告
- LeetCode-Add Binary-解题报告
- LeetCode-Add Digits-解题报告
- 【LeetCode解题报告】Add Digits
- 【LeetCode】 Add Digits 解题报告
- [LeetCode] Add Binary 解题报告
- 【LeetCode】Add Binary 解题报告
- Leetcode-415. Add Strings
- LeetCode 415. Add Strings
- 手握数据,掌控未来(一)
- 初涉VS2010 关于调试下输入后enter直接退出问题
- LC138. Copy List with Random Pointer
- php通过拓展ssh2控制linux
- Android面试题(1)
- [LeetCode] 415. Add Strings 解题报告
- 内部类
- 快速搭建github.io博客
- Android 圆盘旋转/飞转菜单(高度定制化)
- linux 创建文件夹删除文件夹
- TortoiseCVS安装使用详解
- 整理的一些常用H5标签
- U3D中Kinect2的基础环境搭建
- 妙用ES6解构和扩展运算符让你的代码更优雅