题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
using System;
using System.Collections.Generic;
using System.Text;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 计算两个数之和
* @param s string字符串 表示第一个整数
* @param t string字符串 表示第二个整数
* @return string字符串
*/
public string solve (string s, string t) {
// write code here
if (string.IsNullOrWhiteSpace(s) && string.IsNullOrWhiteSpace(t))
return string.Empty;
if (string.IsNullOrWhiteSpace(s))
return t;
if (string.IsNullOrWhiteSpace(t))
return s;
if (t.Length > s.Length) {
string strT = t;
t = s;
s = strT;
}
int nC = 0;
int[] cArr = new int[s.Length];
for (int i = s.Length - 1; i >= 0; i--) {
int nTIndex = i - s.Length + t.Length;
int nS = nC + s[i] - '0' + (nTIndex < 0 ? 0 : t[nTIndex] - '0');
nC = nS / 10;
cArr[i] = nS % 10;
}
return nC > 0 ? "1" + string.Join("", cArr) : string.Join("", cArr);
}
}
查看14道真题和解析
