Code Wars - Sum The Strings

Breaking down code war challenges in a simple and understandable way.

The Problem Statement

Create a function that takes 2 integers in form of a string as an input, and outputs the sum (also as a string):

Example: (Input1, Input2 -->Output)

"4", "5" --> "9" "34", "5" --> "39" "", "" --> "0" "2", "" --> "2""-5", "3" --> "-2" // Notes: If either input is an empty string, consider it as zero.

Analysis -Breaking down the question

If we add two strings it doesn’t perform addition. Instead, it will join them together. For example, let’s take the first example of "4", "5" --> "9" -This is what we expected but we will get "45" in return.

So, Let’s see how we can solve this problem.

The Solution

Create a basic function with two strings as inputs

function sumStr(a,b) {

  }

First, we need to convert the a, b to numbers to get the desired result. For that, we can use Number( ) to convert it to an integer.

function sumStr(a,b) {
   return Number(a)+Number(b) //The result will be 9 (refer to above example)
  }

But we need to change it back to a string. For that, we can use toString( ) as below.

function sumStr(a,b) {
   return (Number(a)+Number(b)).toString(); //The result will be 9 (refer to above example)
  }

sumStr("4", "5") //"9"

At this point, if the a or b is an empty string the function will return the other string. We can use if condition to check the string is empty or 0 as below.

function sumStr(a,b) {
  if (a ==0 || b==0){
    return "0"
  }else {
     return (Number(a)+ Number(b)).toString();
  }
  }

The function will check if the a or b is 0 and if it is true, returns 0. Otherwise, the else block will be executed.

Final Words

If you enjoyed this challenge, subscribe to my newsletter above and you will receive code war solutions right to you.

Follow me on Github to see the solutions to these challenges before I break down here on Hashnode.