题解 | #大数加法#
大数加法
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) { // 让s是最长的数字 if(s.length() < t.length()){ String temp = s; s = t; t = temp; } StringBuilder sb = new StringBuilder(); char[] num1 = s.toCharArray(); char[] num2 = t.toCharArray(); int len1 = num1.length; // len1最长 int len2 = num2.length; int carry = 0; // 进位 for(int i=0 ; i<len2 ; i++){ // 注意我们的数组下标,要从最右边开始哦!就想一想小学的加法原理就很好理解了~ int add = carry + (num1[len1-1-i]-'0') + (num2[len2-1-i]-'0'); // 进位+各个位 int thisPosition = add%10; carry = add/10; sb.append(thisPosition); //将该位拼接到字符串 } // 接下来处理长的数字的剩下位 for(int i=len2 ; i<len1 ; i++){ int add = carry + (num1[len1-1-i]-'0'); // 进位+剩下长数字的位 int thisPosition = add%10; carry = add/10; sb.append(thisPosition); //将该位拼接到字符串 } // 再处理末尾 if(carry != 0){ sb.append(carry); } // 记得翻转sb,从而得到结果。还是老样子,想一想小学的加法原理就很好理解了~ return sb.reverse().toString(); } }