有几个要注意的点
1、字符串可以很长,直接强转相加是肯定不行的,会超出。
2、组合字符串不能直接相加,否则内存会超。必须要使用 StringBuilder,StringBuffer处理
3、看了解题,还可以用BigInteger 直接解(恕在下先前不知道)
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 计算两个数之和
* @param s string字符串 表示第一个整数
* @param t string字符串 表示第二个整数
* @return string字符串
*/
public String solve (String s, String t) {
// write code here
StringBuilder str = new StringBuilder();
// String str = "";
int add = 0;
int num = 1;
for (int i = Math.max(s.length(), t.length()); i > 0; i--) {
char chari = 0;
char charj = 0;
int index = s.length() - num;
if (index >= 0) {
chari = s.charAt(index);
}
int index2 = t.length() - num;
if (index2 >= 0) {
charj = t.charAt(index2);
}
int a = 0;
int b = 0;
if (Character.isDigit(chari)) {
a = chari - '0';
}
if (Character.isDigit(charj)) {
b = charj - '0';
}
// try{
// a = Integer.parseInt(String.valueOf(chari));
// }catch(Throwable e){
// }
// try{
// b = Integer.parseInt(String.valueOf(charj));
// }catch(Throwable e){
// }
str.insert(0, (a + b + add) % 10);
add = (a + b + add) / 10;
num++;
}
if (add != 0) {
str.insert(0, add);
}
return str.toString();
}
}