题目

415. 字符串相加

题解

代码

import java.util.*;

public class code415 {

    public static String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        int carry = 0;
        while (i >= 0 || j >= 0) {
            int n1 = (i >= 0) ? num1.charAt(i) - '0' : 0;
            int n2 = (j >= 0) ? num2.charAt(j) - '0' : 0;
            int temp = n1 + n2 + carry;
            carry = temp / 10;
            sb.append(temp % 10);
            i--;
            j--;
        }
        if (carry == 1) {
            sb.append(carry);
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String num1 = sc.nextLine();
            String num2 = sc.nextLine();
            String res = addStrings(num1, num2);
            System.out.println(res);
        }
    }
}

参考

  1. Add Strings (双指针法)
  2. Java 同时遍历两个字符串
  3. Java StringBuffer reverse()方法
  4. StringBuilder和StringBuffer还有String的区别