Algorithm


Problem Name: 415. Add Strings

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

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

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

 

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"

 

Constraints:

  • 1 <= num1.length, num2.length <= 104
  • num1 and num2 consist of only digits.
  • num1 and num2 don't have any leading zeros except for the zero itself.
 

Code Examples

#1 Code Example with C Programming

Code - C Programming


char* addStrings(char* num1, char* num2) {
    int one, k, i;
    int l1 = strlen(num1);
    int l2 = strlen(num2);
    int l = l1 > l2 ? l1 : l2;
    char c1, c2;
    char *s, *buff;
    
    buff = malloc((l + 2) * sizeof(char));
    //assert(buff);
    
    i = l + 2;
    buff[-- i] = 0;  // null terminated
    one = 0;
    while (l1 > 0 || l2 > 0) {
        c1 = l1 > 0 ? num1[-- l1] : '0';
        c2 = l2 > 0 ? num2[-- l2] : '0';
        k = c1 - '0' + c2 - '0' + one;
        one = k / 10;
        k = k % 10;
        buff[-- i] = k + '0';
    }
    if (one) {
        buff[-- i] = '1';
        //assert(i == 0);
        s = buff;
    } else {
        s = malloc((l + 2) * sizeof(char));
        //assert(s);
        strcpy(s, &buff[i]);
        free(buff);
    }
    return s;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num1 = "11", num2 = "123"

Output

x
+
cmd
"134"

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
  public String addStrings(String num1, String num2) {
    int carry = 0;
    StringBuilder sb = new StringBuilder();
    int idxOne = num1.length() - 1;
    int idxTwo = num2.length() - 1;
    while (idxOne >= 0 || idxTwo >= 0 || carry > 0) {
      if (idxOne >= 0 && idxTwo >= 0) {
        carry += Character.getNumericValue(num1.charAt(idxOne--)) + Character.getNumericValue(num2.charAt(idxTwo--));
      } else if (idxOne >= 0 && idxTwo  <  0) {
        carry += Character.getNumericValue(num1.charAt(idxOne--));
      } else if (idxOne < 0 && idxTwo >= 0) {
        carry += Character.getNumericValue(num2.charAt(idxTwo--));
      }
      sb.append(carry % 10);
      carry = carry > 9 ? carry / 10 : 0;
    }
    return sb.reverse().toString();
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num1 = "11", num2 = "123"

Output

x
+
cmd
"134"

#3 Code Example with Javascript Programming

Code - Javascript Programming


const addStrings = function(num1, num2) {
  let sb = "";
  let carry = 0;
  for (
    let i = num1.length - 1, j = num2.length - 1;
    i >= 0 || j >= 0 || carry == 1;
    i--, j--
  ) {
    let x = i  <  0 ? 0 : +num1.charAt(i);
    let y = j < 0 ? 0 : +num2.charAt(j);
    sb = (+(x + y + carry) % 10) + sb;
    carry = x + y + carry >= 10 ? 1 : 0;
  }
  return sb;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
num1 = "456", num2 = "77"

Output

x
+
cmd
"533"

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        return "".join(str(sum([(ord(num1[i])-ord("0"))*(10**(len(num1)-1-i)) for i in range(len(num1))]+[(ord(num2[i])-ord("0"))*(10**(len(num2)-1-i)) for i in range(len(num2))])))
Copy The Code & Try With Live Editor

Input

x
+
cmd
num1 = "456", num2 = "77"

Output

x
+
cmd
"533"

#5 Code Example with C# Programming

Code - C# Programming


using System.Linq;
using System.Text;

namespace LeetCode
{
    public class _0415_AddStrings
    {
        public string AddStrings(string num1, string num2)
        {
            var sb = new StringBuilder();
            int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
            while (i >= 0 && j >= 0)
            {
                var value = num1[i--] - '0' + num2[j--] - '0' + carry;

                var digit = value % 10;
                carry = value / 10;

                sb.Append(digit);
            }

            while (i >= 0)
            {
                var value = num1[i--] - '0' + carry;
                var digit = value % 10;
                carry = value / 10;
                sb.Append(digit);
            }

            while (j >= 0)
            {
                var value = num2[j--] - '0' + carry;
                var digit = value % 10;
                carry = value / 10;
                sb.Append(digit);
            }

            if (carry != 0)
                sb.Append(carry);

            return new string(sb.ToString().Reverse().ToArray());
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num1 = "0", num2 = "0"

Output

x
+
cmd
"0"
Advertisements

Demonstration


Previous
#414 Leetcode Third Maximum Number Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#416 Leetcode Partition Equal Subset Sum Solution in C, C++, Java, JavaScript, Python, C# Leetcode