I have this weird craving for writing super short code, like writing entire functions in a single line. I do not recommend doing it that way, code readability is many times more important than your code being small in size. But I do it sometimes as a fun activity, just to check if I can do something.
So a friend approached me with a problem called the “step number problem” where you take a number and return true if all the digits differ from the neighbour by 1, either positive or negative.
545678 -> True45654 -> True12345 -> True13573 -> False12145 -> False
Important note: In my score for shortness, I take into account the number of tokens used and not the actual number of characters. Therefore according to my standard, using a variable n instead of variable number doesn’t make it any shorter.
Step 1: Split digits
There are mathematical ways to do this, for example, by taking repeated %10, till the number is > 0. But I went for the convert to string and split approach. I don’t see big performance impacts.
Step 1.1: Convert number to string
There are few ways to do this…
1. number.toString()2. String(number)3. number + ""