#Leetcode# 415. Add Strings

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

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) {
    string c = "";
    int len1 = num1.length();
    int len2 = num2.length();
    int len = max(len1, len2);
    for(int i = len1; i < len; i ++)
        num1 = "0" + num1;
    for(int i = len2; i < len; i ++)
        num2 = "0" + num2;
    int ok = 0;
    for(int i = len - 1; i >= 0; i --) {
        char temp = num1[i] + num2[i] - '0' + ok;
        if(temp > '9') {
            ok = 1;
            temp -= 10;
        }
        else ok = 0;
        c = temp + c;
    }
    if(ok) c = "1" + c;
    return c;
    }
};

  大数加法

原文地址:https://www.cnblogs.com/zlrrrr/p/10691881.html