两个字符串形式大数相加,类似lc02

思想

  1. 从字符串最后一位对应求和
  2. 对所求的和整除10,得到进位位的值temp
  3. 对所求的和取余10,得到该位的值
  4. 如果某一字符串已读取完毕,则默认赋值为0
  5. 答案由每位计算出来的值插入到字符串首位得到

代码实现

    private static StringBuilder add(String a, String b) {
        StringBuilder ans = new StringBuilder();
        int lena = a.length() - 1;
        int lenb = b.length() - 1;
        int temp = 0;
        while (lena >= 0 || lenb >= 0 || temp != 0){
            int num1 = lena >= 0 ? a.charAt(lena) - '0' : 0;
            int num2 = lenb >= 0 ? b.charAt(lenb) - '0' : 0;
            int sum = num1 + num2 + temp;
            ans.insert(0,(sum % 10));
            temp = sum / 10;
            lena = lena - 1 >= 0 ? lena - 1 : -1;
            lenb = lenb - 1 >= 0 ? lenb - 1 : -1;
        }
        return ans;
    }