题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
按正常加法思维,简单易懂。
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ public String solve (String s, String t) { // write code here if(s.length()==0) {return t;} if(t.length()==0) {return s;} String sum = ""; String[] strArray = getComparedStr(s,t); return computStr(strArray); } public String computStr(String[] strArray){ String longStr = strArray[0]; String shortStr = strArray[1]; int n = 0; StringBuilder now = new StringBuilder(); int[] sum; for(int i = longStr.length()-1, j = shortStr.length()-1;i>=0; i--, j--) { char shortChar = j>=0?shortStr.charAt(j):'0'; sum = sumOneChar(shortChar, longStr.charAt(i), n); n = sum[0]; now.insert(0, sum[1]); } if(n != 0) { now.insert(0, n); } return now.toString(); } public int[] sumOneChar(char a, char b, int n) { int[] sum = {0, 0}; int res = (a - '0') + (b - '0') + n; sum[1] = res%10; sum[0] = res/10; return sum; } public String[] getComparedStr(String s, String t) { String res[] = {"",""}; if(s.length()>t.length()){ res[0] = s; res[1] = t; } else{ res[0] = t; res[1] = s; } return res; } }