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:

  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. }





以上是关于415.两个字符串相加 Add Strings的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode415Add Strings

415. Add Strings

[LeetCode]415. 字符串相加43. 字符串相乘

415. Add Strings

leetcode-415. Add Strings

415. Add Strings