Character Count Algorithm — Solution One

Sejan Miah
killingMeSwiftly
Published in
2 min readAug 31, 2017

Today we will analyze an algorithm I was asked to solve recently.

Question: Write a that counts the total number of characters of every number between two numbers (inclusive) spelled out, with whitespace, hyphens and “and” omitted. countCharacters(from: 1, to: 3)” should return “11”

“countCharacters(from: 41, to: 41)” should return “8”

The first thing I was thinking is that I know Swift has a method that converts numbers into their respective word form. Upon doing research on stack overflow, I realized that I could extend the struct Int and add a new method that would invoke the NumberFormatter class and return the string/word form of the respective number I was looking for.

Let’s test out if this actually works.

It does, but there’s a problem, we have a hyphen between the words twenty and one. Upon further investigation it became evident that there were spaces throughout certain words as well. However, there’s a method you can use to fix that.

Let’s dive into the function now.

Let’s test this out to see if it’s working.

In the next few days I will be posting a solution without a helper or conversion function. I hope you have enjoyed this post, please feel free to play around with the NumberFormatter class. There is always a way to find a solution to your problem swiftly.

--

--