[LeetCode] Add Strings

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.

给定两个只含有数字字符串,将字符串中的数字和返回一个字符串。并且要求不能使用整数类库及将输入直接转换成整数。这需要对两个字符串中数字对位相加并处理相加所得的进位。每完成一位的数相加,把它放去结果字符串中。最后将所得的结果字符串数组反转即可。

class Solution {
public:
    string addStrings(string num1, string num2) {
        string s;
        int carry = 0;
        int i = num1.size() - 1;
        int j = num2.size() - 1;
        while (i >= 0 || j >= 0 || carry) {
            int sum = 0;
            if (i >= 0) {
                sum = sum + num1[i] - '0';
                i--;
            }
            if (j >= 0) {
                sum = sum + num2[j] - '0';
                j--;
            }
            sum = sum + carry;
            carry = sum / 10;
            sum = sum % 10;
            s = s + to_string(sum);
        }
        reverse(s.begin(), s.end());
        return s;
    }
};
// 16 ms

 

posted @ 2017-07-19 17:06  immjc  阅读(109)  评论(0编辑  收藏  举报