头插法
import java.util.*;
public class Solution {
public String solve(String s, String t) {
StringBuilder sb = new StringBuilder();
int i = s.length() - 1, j = t.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry != 0) {
int x = i < 0 ? 0 : s.charAt(i--) - '0';
int y = j < 0 ? 0 : t.charAt(j--) - '0';
int sum = x + y + carry;
sb.insert(0, sum % 10);
carry = sum / 10;
}
return sb.toString();
}
}
尾插法
import java.util.*;
public class Solution {
public String solve(String s, String t) {
StringBuilder sb = new StringBuilder();
int i = s.length() - 1, j = t.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry != 0) {
int x = i < 0 ? 0 : s.charAt(i--) - '0';
int y = j < 0 ? 0 : t.charAt(j--) - '0';
int sum = x + y + carry;
sb.append(sum % 10);
carry = sum / 10;
}
return sb.reverse().toString();
}
}
Stack
import java.util.*;
public class Solution {
public String solve(String s, String t) {
Stack<Integer> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
int i = s.length() - 1, j = t.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry != 0) {
carry += i >= 0 ? s.charAt(i--) - '0' : 0;
carry += j >= 0 ? t.charAt(j--) - '0' : 0;
stack.push(carry % 10);
carry /= 10;
}
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.toString();
}
}