Feature #1: Add Likes
Implementing the "Add Likes" feature for our "Twitter" project.
We'll cover the following...
Description
For the first feature of the Twitter application, we are creating an API that calculates the total number of likes on a person’s Tweets. For this purpose, your team member has already extracted the data and stored it in a simple text file for you. You have to create a module that takes two numbers at a time and returns the sum of the numbers. The inputs were extracted from a text file, so they are in the form of strings. The limitation of the API is that we want all of the values to remain strings. We cannot even convert the string to numbers temporarily.
For example, let’s say you are given the strings "1545"
and "67"
as input. Your module should not convert these into integers while computing the sum and return "1612"
.
Solution
To solve this problem, we will do digit-by-digit addition because we cannot convert the strings to integers. The algorithm for decimal addition is given below:
-
First, we will initialize an empty
res
variable. -
Then, we will initialize the
carry
as0
. -
Next, we will set two pointers,
p1
andp2
, that point to the end oflike1
andlike2
, respectively. -
We will traverse the strings from the end using
p1
andp2
and stop when both strings are done. -
We will set
x1
equal to a digit from stringlike1
at indexp1
. Ifp1
has reached the beginning oflike1
, we will setx1
to0
. -
We will do the same for
x2
, settingx2
equal to the digit from stringlike2
at indexp2
. If p2 has reached the beginning oflike2
, we will setx2
to0
. -
Now, we will compute the current value using
value = (x1 + x2 + carry) % 10
. Then, we will update the carry, like so:carry = (x1 + x2 + carry) / 10
. -
We will append the current value to the result.
-
If both of the strings are traversed but the
carry
is still non-zero, we will append thecarry
tores
as well. -
At last, we will reverse the result, convert it to a string, and return that string.
The implementation of this algorithm is given below:
function add_likes(like1, like2){var res = []var carry = 0var p1 = like1.length - 1var p2 = like2.length - 1while (p1 >= 0 || p2 >= 0){var x1var x2if(p1 >= 0)x1 = like1.charCodeAt(p1) - '0'.charCodeAt(0)elsex1 = 0if(p2 >= 0)x2 = like2.charCodeAt(p2) - '0'.charCodeAt(0)elsex2 = 0;value = (x1 + x2 + carry) % 10carry = Math.floor((x1 + x2 + carry) / 10)res.push(value)p1 -= 1p2 -= 1}if (carry != 0)res.push(carry)return res.reverse().join('')}// Driver codeconsole.log(add_likes("1545", "67"))
Time complexity | Space complexity |
---|---|