将两个字符串逆置
然后维护s为最长串进行遍历相加 注意是否有进位
public class Solution {
int carry = 0;
public void add(StringBuilder sb ,char x ,char y){
int sum = x -'0' + y - '0' + carry;//相加
Integer tmp = sum%10;
String c = tmp.toString();
sb.append(c);//追加字符串
carry = sum/10;//维护进位
}
public String solve (String s, String t) {
if(s.length() < t.length()){
String tmp = s;
s = t;
t = tmp;
}//维护s为最长字符串
s = new StringBuffer(s).reverse().toString();//反转字符串
t = new StringBuffer(t).reverse().toString();//反转字符串
StringBuilder sb = new StringBuilder();
for(int i = 0;i < t.length();i++){
add(sb,s.charAt(i),t.charAt(i));
}
for(int i = t.length();i < s.length();i++){
add(sb,s.charAt(i),'0');
}
if(carry == 1) sb.append('1');//如果有进位追加1
return sb.reverse().toString();
}
}