1. 题目
2. 思路
(1) 模拟法
- 从低位开始模拟相加,记录进位的大小,加到高一位的结果中。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public String solve(String s, String t) {
char[] chars1 = s.toCharArray();
char[] chars2 = t.toCharArray();
int n1 = chars1.length - 1;
int n2 = chars2.length - 1;
int last = 0;
StringBuilder sb = new StringBuilder();
while (n1 >= 0 && n2 >= 0) {
int sum = chars1[n1] - '0' + chars2[n2] - '0' + last;
last = sum / 10;
sb.append(sum % 10);
n1--;
n2--;
}
while (n1 >= 0) {
int sum = chars1[n1] - '0' + last;
last = sum / 10;
sb.append(sum % 10);
n1--;
}
while (n2 >= 0) {
int sum = chars2[n2] - '0' + last;
last = sum / 10;
sb.append(sum % 10);
n2--;
}
if (last > 0) {
sb.append(last);
}
return sb.reverse().toString();
}
}
|