题解 | #大数加法#
大数加法
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.equals("")){
return t;
}else if(t.equals("")){
return s;
}
//让s为较长的,t为较短的
if(s.length() < t.length()){
String temp = s;
s = t;
t = temp;
}
int i=s.length()-1;
int carry = 0;//进位\
//字符数组存储结果
char[] ret = new char[s.length()];
//遍历字符串,从末尾相加,在短的存在的情况下加短的不存在不加
while(i>=0){
int tmp = carry + s.charAt(i)-'0';
//计算出此时较短字符串下表
int j = t.length()-s.length()+i;
if(j>=0){
tmp += t.charAt(j)-'0';
}
carry = tmp/10;
tmp = tmp%10;
//赋值
ret[i] = (char) (tmp+'0');
//向前移动一位
i--;
}
String output = String.valueOf(ret);
//当还有进位时
if(carry==1){
output = '1'+output;
}
return output;
}
}

