LeetCode415. Add Strings小学生都会

来源:互联网 发布:javascript与html论文 编辑:程序博客网 时间:2024/04/30 08:44

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) {
        int eb = 0;
        int len = max(num1.size(), num2.size());
        vector<char> vc;
        char a, b;
        for (int i = 0; i < len; i++)
        {
            if (i < num1.size()) {
                a = num1[num1.size()-1-i];    
            } else {
                a = '0';
            }
            if (i < num2.size()) {
                b = num2[num2.size()-1-i];
            } else {
                b = '0';
            }
            
            int val = a - '0' + b - '0' + eb;
            eb = val / 10;
            char c = '0' + val % 10;
            vc.push_back(c);
        }
        if (eb > 0) {
            vc.push_back('0' + eb);
        }
        string result(vc.rbegin(), vc.rend());
        return result;
    }
};


0 0
原创粉丝点击