要想着把每一位拆出来运算
要点:
数组将其置为小下标为低位,大下标为高位,方便后面代码逻辑的编写
res[i] = res[i] + ss[i] + ts[i];
如果res[i] > 9 , res[i + 1] + 1, res[i] - 10;import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ public String solve (String s, String t) { // write code here int[] ss = new int[s.length()]; int[] ts = new int[t.length()]; for (int i = 0; i < s.length(); i++) { ss[i] = s.charAt(s.length() - 1 - i) - '0'; } for (int i = 0; i < t.length(); i++) { ts[i] = t.charAt(t.length() - 1 - i) - '0'; } int max = s.length() > t.length() ? s.length() : t.length(); int min = s.length() < t.length() ? s.length() : t.length(); int[] res = new int[max + 1]; for (int i = 0; i < min; i++) { res[i] = res[i] + ss[i] + ts[i]; if (res[i] > 9) { res[i + 1]++; res[i] -= 10; } } if (s.length() > t.length()) { for (int i = min; i < max; i++) { res[i] += ss[i]; if (res[i] > 9) { res[i + 1]++; res[i] -= 10; } } } else { for (int i = min; i < max; i++) { res[i] += ts[i]; if (res[i] > 9) { res[i + 1]++; res[i] -= 10; } } } StringBuffer result = new StringBuffer(); if (res[max] != 0) { result.append(res[max]); } for (int i = max - 1; i >= 0; i--) { result.append(res[i]); } return result.toString(); } }