public class Solution
{
public string AddStrings(string num1, string num2)
{
//判断num1和num2的长度,进行对齐
if (num1.Length < num2.Length)
{
//将num1前补0
var zerocount = num2.Length - num1.Length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zerocount; i++)
{
sb.Append("0");
}
num1 = sb.ToString() + num1;
}
else
{
var zerocount = num1.Length - num2.Length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zerocount; i++)
{
sb.Append("0");
}
num2 = sb.ToString() + num2;
}
//对齐之后,从低位到高位依次进行加运算
var step = 0;//进位
var list1 = num1.Reverse().ToList();
var list2 = num2.Reverse().ToList();
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < list1.Count(); i++)
{
var n1 = Convert.ToInt32(list1[i].ToString());
var n2 = Convert.ToInt32(list2[i].ToString());
var n = n1 + n2 + step;
sb2.Append((n % 10).ToString());
if (n >= 10)
{
step = 1;
}
else
{
step = 0;
}
}
if (step == 1)
{
sb2.Append("1");
}
var list = sb2.ToString().Reverse();
StringBuilder sb3 = new StringBuilder();
foreach (var c in list)
{
sb3.Append(c);
}
var result = sb3.ToString();
return result;
}
}
https://leetcode.com/problems/add-strings/#/description