首页 > 考试 > 其他 >

leetcode---Add Strings

2017-04-15

leetcode---Add Strings,Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2。

leetcode---Add Strings,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] - &#39;0&#39; - &#39;0&#39;;
        }
        while(i >= 0)
        {
            arr[k++] = num1[i--] - &#39;0&#39;;
        }
        while(j >= 0)
        {
            arr[k++] = num2[j--] - &#39;0&#39;;
        }

        // 进位
        int c = 0;
        for(i=0; i=0; i--)
        {
            s << arr[i];
        }
        return s.str();
    }
};
相关文章
最新文章
热点推荐