Add Strings

Feb 7, 202310 mins read

Straight to the Point !

You've arrived at our page in a hurry to find a brute force javascript solution. Here we go Step 1: Parse Int the two numbers
Step 2: add the two numbers using "+" operator
Step 3: convert it to two string.

1var addStrings = function(num1, num2) {
2 const n1 = parseInt(num1)
3 const n2 = parseInt(num2)
4 return (n1+n2).toString();
5};

Prior to reviewing several optimized solutions below, It is worthwhile to read the article in its entirety for a deeper understanding.

Note: This is one of the Facebook interview question and Refer to Similar Leet code problem as well - 415. Add Strings

Table of Contents

Problem Statement

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

  1. 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.
1String addStrings(String num1, String num2)

Constraints

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

Expected

  1. Sum of Two String return in String

Test Cases

  1. Input = num1 = "11", num2 = "123" Output = "134"
  2. Input = num1 = "456", num2 = "77" Output = "533"
  3. Input = num1 = "0", num2 = "0" Output = "0"

Foot Note

Complexity 1: Possible of lesser as num1 and greater number as num2. Complexity 2: Result and Inputs are string. so we have deal with carefully. Complexity 3: There is possible we get big integer since its string, we need to handle that as well.

Solution Intro

Lets see the list of approaches and their complexities.

  1. Approach 1: Using Big Int.
  2. Approach 2: Elementary Math.
  3. Time Optimized: Yet to update.
  4. Space Optimized: Yet to update.

ApproachTime ComplexitySpace Complexity
1Brute ForceO(n)O(n)
2Approach 1 - Using Big IntO(n)O(n)
3Approach 2 - Elementary MathO(max(N1​,N2​))O(max(N1​,N2​))
4Time OptimizedO(n)O(n)
5Memory OptimizedO(n)O(n)

Solutions

With no further due, lets take a example of code solutions.

Brute Force

Description

1var addStrings = function(num1, num2) {
2 const n1 = parseInt(num1)
3 const n2 = parseInt(num2)
4 return (n1+n2).toString();
5};

Approach 1 Using Big Int

Step 1: Convert the both num1 and num2 parameters to Big Integers.
Step 1.1: Add both big integers and store it in result variable.
Step 2: Pass it to String constructor and return the value.
Step 2.1: Alternative - Convert the big integer result to string using toString().
Step 2.2: Alternative - Convert to String using template literals.

1var addStrings = function(num1, num2) {
2 const result = BigInt(num1) + BigInt(num2);
3 return String(result);
4 // return result.toString() // OR
5 // return `${result}` // OR
6};

Approach 1 Elementary Math

Step 1: Initialize result as empty string and carry as zero.
Step 2: Store both numbers length to additional variable as num1Length, num2Length.
Step 3: Run while until any length variable is greater than or equal to zero.
Step 4: Compute the iterated index value to additional variable as num1Result, num2Result.
Step 5: IF index is greater than or equal to zero store the index value subtract with 0 zero string else numeric 0 zero.
Step 6: Initialize value adding num1Result and num2Result module by 10
Step 7: Update carry adding num1Result and num2Result divided by 10 with
Step 8: Append the value first to result variable as suffix.
Step 9: decrement the num1Length and num2Length.
Step 10: Append the carry first and result variable as suffix to the same result only if carry is not equal to 0.
Step 11: return computed string.

1function addStrings(num1, num2) {
2 let result = '';
3 let carry = 0;
4
5 let num1Length = num1.length - 1;
6 let num2Length = num2.length - 1;
7
8 while (num1Length >= 0 || num2Length >= 0) {
9 let x1 = num1Length >= 0 ? num1[num1Length] - '0' : 0;
10 let x2 = num2Length >= 0 ? num2[num2Length] - '0' : 0;
11 let value = (x1 + x2 + carry) % 10;
12 carry = ((x1 + x2 + carry) / 10) | 0;
13 result = `${value}${result}`
14 num1Length--;
15 num2Length--;
16 }
17
18 if (carry != 0) {
19 result = `${carry}${result}`
20 }
21
22 return result
23}

Time Optimized

Coming Soon...

1Code goes here...

Space Optimized

Coming Soon...

1Code goes here...

Similar Questions

There is few more questions by data structure type which is similar problems. checkout below questions.

Integer - Sum of Two Integers

Given two integers a and b, return the sum of the two integers without using the operators + and -.

Input: a = 1, b = 2
Output: 3
371. Sum of Two Integers for more details

Array - Add to Array Form of Integer

The array-form of an integer num is an array representing its digits in left to right order.

For example, for num = 1321, the array form is [1,3,2,1].

989. Add to Array-Form of Integer for more details

Linked List - Plus One

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

66. Plus One for more details

Linked List - Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

2. Add Two Numbers for more details

Linked List - Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

445. Add Two Numbers II for more details