415. Two strings added add Strings

Source: Internet
Author: User


Given non-negative Numbersnum1andnum2Represented as String, return the sum ofnum1andnum2.

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



From for notes (Wiz)

415. Two strings added add Strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.