题目
Given two non-negative integers num1
and num2
represented as string, return the sum ofnum1
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.
题意
给定两个非负整数num1 和 num2 ,以字符串的形式表示,返回num1和num2的和。(有一些限制,见上面的note)
分析及代码
- 【方案机制】题目的要求是让你去模拟加法的执行过程。需要了解深入计算的细节(按位相加,进位机制)
- 【程序机制】为了达到按位相加,进位的效果,在程序中需要分别设置相关的信息去记录。并且运算的规则需要符合加法的原理。
- 【游标】为num1,num2分别分配了游标,原因是两个num长度可能不一致,并且加法需要是从低位进行,而数字中的最低位却是字符串中数组下标最大的。
public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
sb.append((x + y + carry) % 10);
carry = (x + y + carry) / 10;
}
return sb.reverse().toString();
}
}