首页 > 代码库 > 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:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Subscribe to see which companies asked this question


  1. public class Solution {
  2. public string AddStrings(string num1, string num2) {
  3. string s = "";
  4. int maxLength = Math.Max(num1.Length, num2.Length);
  5. num1 = num1.PadLeft(maxLength, ‘0‘);
  6. num2 = num2.PadLeft(maxLength, ‘0‘);
  7. int carry = 0;
  8. int digit = 0;
  9. int i = maxLength - 1;
  10. while (i >= 0 || carry>0)
  11. {
  12. digit = carry;
  13. if (i >= 0)
  14. {
  15. digit += ((int)num1[i] - 48) + ((int)num2[i] - 48);
  16. }
  17. if (digit >= 10)
  18. {
  19. carry = digit / 10;
  20. }
  21. else
  22. {
  23. carry = 0;
  24. }
  25. s = (digit % 10).ToString() + s;
  26. i--;
  27. }
  28. return s;
  29. }
  30. }



来自为知笔记(Wiz)


415.两个字符串相加 Add Strings