码迷,mamicode.com
首页 > 其他好文 > 详细

415.两个字符串相加 Add Strings

时间:2017-01-11 07:51:13      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:padding   ati   bottom   字符串   line   tty   为知笔记   code   ref   


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

标签:padding   ati   bottom   字符串   line   tty   为知笔记   code   ref   

原文地址:http://www.cnblogs.com/xiejunzhao/p/7c6d566a6c48ae237cd93d13938158bc.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!