LeetCode problem #8 — String to Integer (JavaScript)
In this LeetCode challenge we’re asked to convert an incoming string to an integer. Now you might be thinking to yourself, “But wait, isn’t that what parseInt
is for? Well you’d be right, and that is why this question is reportedly one of the most disliked on all of LeetCode. That, and the fact it has a very long list of (in my opinion unreasonable) conditions.
Solution #1: parseInt()
First off, let’s look at how we’d solve this using the tools JavaScript gives us:
It’s simple, elegant, fast, and could be simplified to 1-4 lines depending on how much readability you’re willing to sacrifice. But if you ask the comments section on LeetCode, you’ll probably get a fair bit of hate for pitching this solution.
Solution #2: So many if statements
Due to the large number of conditions applied for this question, it’s difficult to come up with anything especially elegant. There can be an infinite number of leading spaces, but a space after the number indicates the end of the number, even if its followed by more numbers. Letters can’t precede the number, but +
and -
can, although not two at a time, and they can’t come afterwards…
See the problem here? Well, here’s the problem in code:
The code is pretty quick, but can definitely be improved. Why didn’t I improve it? Because parseInt()
exists for a reason… this reason!