leetcode415

时间:2023-03-08 17:45:27
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 = ; i < zerocount; i++)
{
sb.Append("");
}
num1 = sb.ToString() + num1;
}
else
{
var zerocount = num1.Length - num2.Length;
StringBuilder sb = new StringBuilder();
for (int i = ; i < zerocount; i++)
{
sb.Append("");
}
num2 = sb.ToString() + num2;
} //对齐之后,从低位到高位依次进行加运算 var step = ;//进位 var list1 = num1.Reverse().ToList();
var list2 = num2.Reverse().ToList();
StringBuilder sb2 = new StringBuilder();
for (int i = ; 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 % ).ToString());
if (n >= )
{
step = ;
}
else
{
step = ;
}
} if (step == )
{
sb2.Append("");
} 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