(字符串)04-大数相加

发布时间 2023-11-26 20:49:54作者: StringBuilder

 1 import java.util.*;
 2 
 3 public class Solution {
 4     /**
 5      * 计算两个数之和
 6      * @param s string字符串 表示第一个整数
 7      * @param t string字符串 表示第二个整数
 8      * @return string字符串
 9      */
10     public String solve (String s, String t) {
11         // 判空入参
12         if (s.length() <= 0) {
13             return t;
14         }
15         if (t.length() <= 0) {
16             return s;
17         }
18         // 让s为较长的t为较短的
19         if (s.length() < t.length()) {
20             String temp = s;
21             s = t;
22             t = temp;
23         }
24         // 进位标志
25         int carry = 0;
26         // 初始返回结果
27         char[] res = new char[s.length()];
28         // 从后往前遍历较长的字符串
29         for (int i = s.length() - 1; i >= 0; i--) {
30             // 获取长字符的数字+进位
31             int temp = s.charAt(i) - '0' + carry;
32             // 获取较短字符的数字
33             int j = i - s.length() + t.length();
34             // 加上短字符的数组
35             if (j >= 0) {
36                 temp += t.charAt(j) - '0';
37             }
38             // 取进位
39             carry = temp / 10;
40             // 去十位
41             temp = temp % 10;
42             // 填充计算结果
43             res[i] = (char)(temp + '0');
44         }
45         // 转换结果的数据格式
46         String output = String.valueOf(res);
47         // 最后的进位
48         if (carry == 1)
49             output = '1' + output;
50         // 返回结果
51         return output;
52     }
53 }