image.png

解题思路

双指针

image.png

  1. class Solution {
  2. public String addStrings(String num1, String num2) {
  3. StringBuilder res = new StringBuilder("");
  4. int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
  5. while(i >= 0 || j >= 0){
  6. int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
  7. int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
  8. int tmp = n1 + n2 + carry;
  9. carry = tmp / 10;
  10. res.append(tmp % 10);
  11. i--; j--;
  12. }
  13. if(carry == 1) res.append(1);
  14. return res.reverse().toString();
  15. }
  16. }