MDGSF Software Engineer

[算法学习][leetcode] 415 Add Strings

2017-08-31
mdgsf
Art

https://leetcode.com/problems/add-strings/description/

题目

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.

题目翻译

题目解析

参考答案

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string addStrings(string num1, string num2) {

        string strResult;
        int iFlag = 0;

        int iIdx1 = num1.size() - 1;
        int iIdx2 = num2.size() - 1;
        while (iIdx1 >= 0 && iIdx2 >= 0)
        {
            int iSum = (num1[iIdx1] - '0') + (num2[iIdx2] - '0') + iFlag;
            if (iSum >= 10)
            {
                iFlag = 1;
                iSum -= 10;
            }
            else
            {
                iFlag = 0;
            }

            strResult.append(1, iSum + '0');

            iIdx1--;
            iIdx2--;
        }

        while (iIdx1 >= 0)
        {
            int iSum = (num1[iIdx1] - '0') + iFlag;
            if (iSum >= 10)
            {
                iFlag = 1;
                iSum -= 10;
            }
            else
            {
                iFlag = 0;
            }

            strResult.append(1, iSum + '0');

            iIdx1--;
        }

        while (iIdx2 >= 0)
        {
            int iSum = (num2[iIdx2] - '0') + iFlag;
            if (iSum >= 10)
            {
                iFlag = 1;
                iSum -= 10;
            }
            else
            {
                iFlag = 0;
            }

            strResult.append(1, iSum + '0');

            iIdx2--;
        }

        if (iFlag > 0)
        {
            strResult.append(1, '1');
        }

        int i = 0;
        int j = strResult.size() - 1;
        while (i < j)
        {
            int temp = strResult[i];
            strResult[i] = strResult[j];
            strResult[j] = temp;
            i++;
            j--;
        }

        return strResult;
    }
};

int main()
{
    string num1 = "1";
    string num2 = "9";
    Solution o;
    string strResult = o.addStrings(num1, num2);
    cout << strResult << endl;
    return 0;
}

weixingongzhonghao

Similar Posts

Comments