415.两个字符串相加 Add Strings
Posted Long Long Journey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了415.两个字符串相加 Add Strings相关的知识,希望对你有一定的参考价值。
Given two non-negative numbers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Subscribe to see which companies asked this question
public class Solution {
public string AddStrings(string num1, string num2) {
string s = "";
int maxLength = Math.Max(num1.Length, num2.Length);
num1 = num1.PadLeft(maxLength, ‘0‘);
num2 = num2.PadLeft(maxLength, ‘0‘);
int carry = 0;
int digit = 0;
int i = maxLength - 1;
while (i >= 0 || carry>0)
{
digit = carry;
if (i >= 0)
{
digit += ((int)num1[i] - 48) + ((int)num2[i] - 48);
}
if (digit >= 10)
{
carry = digit / 10;
}
else
{
carry = 0;
}
s = (digit % 10).ToString() + s;
i--;
}
return s;
}
}
以上是关于415.两个字符串相加 Add Strings的主要内容,如果未能解决你的问题,请参考以下文章