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, our team member has already extracted the data and stored it in a simple text file for us. We 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 we are given the strings "1545"
and "67"
as input. Our 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:
import Swiftfunc addLikes(like1: String, like2: String) -> String {var res: String = ""var carry: Int = 0var p1: Int = like1.count - 1var p2: Int = like2.count - 1while p1 >= 0 || p2 >= 0 {var x1: Int = 0var x2: Int = 0if p1 >= 0 {let constant:Character = "0"x1 = Int(like1[like1.index(like1.startIndex, offsetBy: p1)].asciiValue!) - Int(constant.asciiValue!)}else{x1 = 0}if p2 >= 0 {let constant:Character = "0"x2 = Int(like2[like2.index(like2.startIndex, offsetBy: p2)].asciiValue!) - Int(constant.asciiValue!)}else {x2 = 0}let value: Int = (x1 + x2 + carry) % 10carry = (x1 + x2 + carry) / 10res += String(value)p1 -= 1p2 -= 1}if (carry != 0) {res += String(carry)}return String(res.reversed())}print(addLikes(like1: "1545", like2: "67"))
Complexity measures
Time complexity | Space complexity |
---|---|