leetcode 415. Add Strings 字符串加法

来源:互联网 发布:fcc 网络中立 编辑:程序博客网 时间:2024/05/22 08:20

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

下面是字符串的加法,很简单,直接看代码

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <bitset>using namespace std;class Solution {public:    string addStrings(string num1, string num2)     {        string res = "";        int i = num1.length() - 1, j = num2.length() - 1;        int jinwei = 0;        while (i >= 0 || j >= 0)        {            int a = i >= 0 ? num1[i] - '0' : 0;            int b = j >= 0 ? num2[j] - '0' : 0;            res = to_string((a + b + jinwei) % 10) + res;            jinwei = (a + b + jinwei) / 10;            i--;            j--;        }        if(jinwei>0)            res = to_string(jinwei) + res;        return res;    }};