Grind 75 Problem 6 - String to Integer (atoi)

https://cplusplus.com/reference/cstdlib/atoi/

Why I never considered that the C++ programming language had its own website, but I find it kind of funny that it does. This problem is a challenge to re-implement the functionality of the atoi C++ function.

I've been thinking about this one a lot, and I'm pretty sure I have a sense of implementation. I actually tried building this already, walked away in the middle, and then came back and I was lost enough that I decided to start from scratch and use this blog post to keep myself on track.

I have a string and I need to convert it to an integer following some specific rules.

If the string starts with whitespace, ignore it.

If the string starts with a + or -, that will be the sign of the integer that returns.

Once we've gone through the optional whitespace in "+", or "-", any character that wants to be returned must be digit 0-9.

The first non-digit character triggers a return of what's been seen so far. If we have a non-digit character before we see a digit character, it returns 0.

Coding plan

1. First, I need to split the array, which is `O(N)`.

2. Then, I need to loop through this array and collect the chars I need. So maybe instead of a for loop I can set the index variable outside of a while loop and we walk through the array while the index char doesn't qualify for the fail conditions listed above and the index is within range of the array.

3. While we don't yet have any digits or sign, ignore white space

4. Store sign if we see it. Only store negative, as positive is the default case

5. Begin storing digit characters once seen

6. Once digits begin, any other char is a fail condition

7. Once we have the sign and digits, calculate the result by multiplying each positional digit by ten to the power of the inverse of the index - so results.length - i - 1, and then adding them together.

So if we have the result array of [3,4,1], we'd 3 by 10 to the power of result.length (3) - i (0) - 1 , which is 3 10 ^ 2, which is 300 + 4 10 ^ 1(40) + 1 * 10 ^ 0 (1).

And then finally, if it's negative, return negative. I think I'm ready to code this.