问题描述
以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
(字符串长度不大于100000,保证字符串仅由’0’~'9’这10种字符组成)
输入描述:
输入两个字符串格式数字
输出描述:
输出数字相加的和
示例
示例1
输入
“1”,“99”
输出
“100”
解决思路
分析
- 从末位向前依次处理,处理进位的情况,需要处理相加和超出最长字符串位数的情况
方法
- 通过循环从末位向前依次处理,处理进位的情况,需要处理相加和超出最长字符串位数的情况
代码实现
// 思路1
public class Solution {
public String solve (String s, String t) {
// write code here
if (s == null && s.length() == 0) {
return t;
}
if (t == null && t.length() == 0) {
return s;
}
if (s.length() < t.length()) {
String temp = s;
s = t;
t = temp;
}
int temp = 0;
int i = s.length() - 1, j = t.length() - 1;
char[] result = new char[s.length()];
while (i >= 0 && j >= 0) {
int a = s.charAt(i) - '0';
int b = t.charAt(j) - '0';
int c = a + b + temp;
if (c >= 10) {
temp = c / 10;
c %= 10;
} else {
temp = 0;
}
result[i] = (char) ('0' + c);
i--;
j--;
}
while (i >= 0) {
int a = s.charAt(i) - '0';
int c = a + temp;
if (c >= 10) {
temp = c / 10;
c %= 10;
} else {
temp = 0;
}
result[i] = (char) ('0' + c);
i--;
}
String val = new String(result);
if (temp > 0) {
return String.valueOf(temp) + val;
}
return val;
}
}
小伙伴如果想测试的话,可以直接到牛客网这个链接做测试