This is the first article of a series I will be publishing to share tips on how to solve popular coding interview questions. If you are still wondering if you need to learn this, you can read my previous article on why developers should solve coding challenges. We would start off by learning how to convert a string to an integer without any in-built methods. A colleague of mine recently got this question in an interview. You may not have learned this yet, but it is pretty easy to solve, let me walk you through it.
The image above depicts what we are expected to achieve and how to achieve that using in-built methods in both JavaScript and Ruby. In order to achieve this without any of the above methods, we need to put into consideration how numbers are formed generally. Every number is a combination of several other numbers added in thousands, hundreds, tens, or units. This dear reader is the key to solving this challenge.
Considering the image above, we can see the several combinations that form the foundation of all numbers. Units are 10⁰, tens are 10¹, hundreds are 10², thousands are 10³, tens of thousands are 10⁴, and so on. Observing carefully, we can see that counting from the left, the power of 10 corresponding to every digit is equal to the difference between the length of the number(how many digits it contains) and the position of the digit.
Now that we understand this dynamic, let us dive into writing the function that solves this problem. We’ll follow the steps below:
- Create an object that maps every string to its number equivalent, this is to enable us to get the right number during our multiplications and additions, or we can also use the ASCII equivalents. Whichever you prefer is fine, I would write solutions using both. It is worthy of note that the ASCII equivalents of numbers range from 48–57.
- Split the string into an array so that we can loop through it.
- Find out the length of the array, so we know how many digits make up the number. Subtract 1 from the length to make up for the fact that index positions in an array are 1 less than the original positions. This is because the digit at the first position will have an index of 0 and so on.
- Start the calculation to multiply every digit by 10 raised to the power of the difference between our length and the position of the digit as we have explained earlier.
- Refactor our code to make it shorter.
In Ruby, this can be solved as shown below;
Using the ASCII equivalents and the JavaScript reduce method, we have;
Refactoring the code using the ASCII equivalents and without the explicit use of multiplication by powers of 10 as suggested by my dear friend Olumide Akinbolajo, we have;
I encourage you to try this several times with different methods, hell yeah! you can even use recursion if that's your thing. If you do have any questions though, please do not hesitate to contact me via Twitter. Happy Coding!!
Top comments (0)