Problem: Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Example:
Input: num1 = "99" num2 = "9" Output: "108"
Approach: Nothing to explain here. Just look at the implementation as the approach is straight forward.
Implementation in C#:
public string AddStrings(string num1, string num2)
{
char[] result = new char[Math.Max(num1.Length, num2.Length) + 1];
int i = num1.Length - 1, j = num2.Length - 1, resultIndex = result.Length - 1, carry = 0;
while (i >= 0 && j >= 0)
{
int sum = (num1[i--] - '0') + (num2[j--] - '0') + carry;
carry = sum / 10;
sum = sum % 10;
result[resultIndex--] = (char)(sum + '0');
}
if (i >= 0)
{
this.SumOneNumWithCarry(result, num1, i, resultIndex, carry);
}
else if (j >= 0)
{
this.SumOneNumWithCarry(result, num2, j, resultIndex, carry);
}
else if (carry > 0)
{
result[0] = (char)(carry + '0');
}
return result[0] != 0 ? new string(result) : new string(result, 1, result.Length - 1);
}
private void SumOneNumWithCarry(char[] result, string num, int index, int resultIndex, int carry)
{
int resultItr = resultIndex;
int numItr = index;
while (numItr >= 0)
{
result[resultItr--] = num[numItr--];
}
if (carry == 1)
{
while (index >= 0)
{
if (num[index] == '9')
{
result[resultIndex--] = '0';
--index;
}
else
{
++result[resultIndex];
return;
}
}
result[0] = '1';
}
}
Complexity: O(Max(length of num1, length of num2))
No comments:
Post a Comment