字符串相加【LC415】
给定两个字符串形式的非负整数
num1
和num2
,计算它们的和并同样以字符串形式返回。
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
简单模拟运算
- 思路:使用双指针从整数的最低位模拟相加操作
- 使用两个指针从整数的低位开始定位字符,模拟相加操作
- 使用变量记录低位的进位,将每位的相加结果放入StringBuilder变量的开头中
class Solution { public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int i = num1.length() - 1, j = num2.length() - 1; int cnt = 0; while (i >= 0 || j >= 0 || cnt != 0){ int val1 = i >= 0 ? num1.charAt(i) - '0' : 0; int val2 = j >= 0 ? num2.charAt(j) - '0' : 0; sb.insert(0,(val1+val2+cnt)%10); cnt = (val1+val2+cnt) / 10; i--; j--; } return new String(sb); } }