leetcode---Add Strings

来源:互联网 发布:mac 安装找不到硬盘 编辑:程序博客网 时间:2024/06/07 09:23

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.

class Solution {public:    string addStrings(string num1, string num2)     {        int n1 = num1.size();        int n2 = num2.size();        int n = max(n1, n2);        int arr[n+2];        int k = 0;        int i, j;        // 相加        for(i=n1-1, j=n2-1; i>=0 && j>=0; i--, j--)        {            arr[k++] = num1[i] + num2[j] - '0' - '0';        }        while(i >= 0)        {            arr[k++] = num1[i--] - '0';        }        while(j >= 0)        {            arr[k++] = num2[j--] - '0';        }        // 进位        int c = 0;        for(i=0; i<k; i++)        {            arr[i] += c;            c = arr[i] / 10;            arr[i] %= 10;            cout << arr[i] << " ";        }        // 最高位的进位        if(c)        {           arr[i] = c;           k++;        }        // 输出        stringstream s;        for(i=k-1; i>=0; i--)        {            s << arr[i];        }        return s.str();    }};
0 0
原创粉丝点击