首页 > 代码库 > 415.两个字符串相加 Add Strings
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;
}
}
来自为知笔记(Wiz)
415.两个字符串相加 Add Strings
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。