Given two non-negative integers 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.
     1 class Solution {
     2 public:
     3     string addStrings(string num1, string num2) {
     4         if (num1.size() < num2.size()) return addStrings(num2, num1);
     5         int extra = 0;
     6         int idx1 = num1.size() - 1;
     7         int idx2 = num2.size() - 1;
     8         while (idx1 >= 0) {
     9             int sum = extra + num1[idx1] - '0';
    10             if (idx2 >= 0)
    11                 sum = sum + num2[idx2] - '0';
    12             num1[idx1] = '0' + sum % 10;
    13             extra = sum / 10;
    14             idx1--;
    15             idx2--;
    16         }
    17         if (extra) num1 = "1" + num1;
    18         return num1;
    19     }
    20 };

     

posted on 2017-05-18 17:07  无惧风云  阅读(114)  评论(0编辑  收藏  举报