Top 5 Programming Languages for Blockchain Development

Blockchain technology has opened up new ways to build decentralized applications that cannot be manipulated or corrupted. Although the initial phase of blockchain development was limited to…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Expanded Form algorithm Solution

As I continue to work on my algorithm chops, I encountered a fun problem: a function that writes numbers in ‘expanded form’. If you pass in the number ‘3,416’ into the function, it should return a string stating ‘3000 + 400 + 10 + 6’. If you pass in ‘900’, it should simply return ‘900’ since there are no additional numbers to add — the form is already ‘expanded.’

In my first attempt I tried to continuously append each expanded number to an existing string. While this sort of worked, it was ridiculously inefficient. I needed to write all sorts of conditionals in order to deal with numbers like ‘900’, ‘0’, or numbers contained 0’s somewhere in the middle, like ‘9,015’. I also needed to write conditionals to address when and where to append a ‘ + ’ to the string and when to identify this character wasn’t needed.

Then I realized if, instead of appending to a string, I pushed each expanded number into an array, and then used a .join(‘ +’ ) method, the logic would always work out and those funky conditionals would be unnecessary.

Let’s look at how I solved the issue:

Here I declare my function, set up an empty array to append our expanded numbers to, and convert the num argument into a string so we can iterate through it, number by number.

Now I need to iterate through this string of the num argument. I also need to set up a zero count — the number of zeros that must be added to the number to expand it. Since this count will always be the number of remaining characters in the string after our current character, you can calculate it like I do below, by taking the length of the string, subtracting the current index of our character, and then subtracting one so the current character isn’t included:

You’ll see what I’ve declared x below — it’s simply so we can keep track of our 0’s, which I’ll add in a while loop:

Now I need to add logic that will prevent us from adding unnecessary 0’s to our number array. Obviously, if the number is 9000, we don’t want to return ‘9000 + 000 + 00 + 0’. We just want ‘9000’. I address by using an if statement to ensure that we’ll only add to our subNum array when the current character isn’t 0. If it isn’t, we’ll use a while loop to add 0’s to the current character until it has the appropriate number of 0’s.

Then all we need to do is join our array items together with a ‘ +’ between each one!

And there we have it!

Here is the whole function:

Happy coding!

Add a comment

Related posts:

NETWORK SCALING

The main goal of scalability is to increase transaction speed (faster finality), and transaction throughput (high transactions per second), without sacrificing decentralization or security…