

LeetCode-415-字符串相加
source link: https://segmentfault.com/a/1190000040788008
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-415-字符串相加
解法一:遍历字符串题目描述:给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
提示:
- num1 和num2 的长度都小于 5100
- num1 和num2 都只包含数字 0-9
- num1 和num2 都不包含任何前导零
- 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
首先,声明一个字符串result为最后的返回值,声明所以为i初始值为0,addOne为进位值初始为0,firstNum和secondNum分别为num1和num2当前索引位的数字,然后开始遍历num1和num2中的元素,处理过程如下:
- 如果i没有超过num1和num2的长度,则分别将num1和num2中当前索引位置的数字赋值给firstNum和secondNum,否则将firstNum和secondNum赋值为0;
- 然后计算
firstNum + secondNum + addOne
结果为sum;- 如果sum大于9,则需要进位,addOne被重置为1,且将
sum-10
添加到result的字符串前面;- 如果sum小于9,则不需要进位,addOne被重置为0,且将
sum
添加到result的字符串前面;最后,判断addOne为1,则将addOne添加到result前面。
最后返回result即为字符串相加的结果。
/** * @Author: ck * @Date: 2021/9/29 8:34 下午 */ public class LeetCode_415 { public static String addStrings(String num1, String num2) { String result = ""; // addOne为进位 int i = 0, addOne = 0, firstNum = 0, secondNum = 0; while (i < num1.length() || i < num2.length()) { if (i < num1.length()) { // num1中当前位的数字 firstNum = num1.charAt(num1.length() - 1 - i) - '0'; } else { firstNum = 0; } if (i < num2.length()) { // num2中当前位的数字 secondNum = num2.charAt(num2.length() - 1 - i) - '0'; } else { secondNum = 0; } int sum = firstNum + secondNum + addOne; if (sum > 9) { result = (sum - 10) + result; addOne = 1; } else { result = sum + result; addOne = 0; } i++; } if (addOne == 1) { result = 1 + result; } return result; } public static void main(String[] args) { // 期望输出: 533 System.out.println(addStrings("456", "77")); } }
【每日寄语】 诚信是做人之母,务实乃成功之道。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK