Algorithms / Extract digits of a number from both ends
Let’s say, we have a problem that requires us to print all the digits of a number from the left to right.
A simple approach would be extracting the digits from the right to the left, storing them in an array, and printing that array in a reverse way.
The time complexity of this algorithm would be
To optimize the space complexity of the above algorithm, we can extract the digits from the left to the right.
We can see that, for a number
And the remainder of the above calculation is actually the number
We already know how to count the digits of a number, it can be obtained by:
So, the algorithm to extract the digits from the left to the right would be:
The new algorithm still has
In line 5, we can also decrease