All posts

Algorithms / Extract digits of a number from both ends

Posted On 04.19.2022

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.

PRINTDIGITSRIGHTTOLEFT(n)
1:digitsempty list
2:while n>0
3:dn mod 10
4:nn÷10
5:push d  digits
6:i:=length of digits
7:while i0
8:ii1
9:print digits[i]

The time complexity of this algorithm would be O(n), with n being the number of digits in the input number. Since we need to allocate a new array, the algorithm would take O(n) space as well.

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 n of k digits, if we divide n by 10k1, the result is the first digit of n, for example, with n=54321, there are k=5 digits:

54321÷104=5

And the remainder of the above calculation is actually the number n without its first digit!

54321 mod 104=4321

We already know how to count the digits of a number, it can be obtained by:

k=log10(n)+1

So, the algorithm to extract the digits from the left to the right would be:

PRINTDIGITSLEFTTORIGHT(n)
1:klog10(n)+1
2:while n>0
3:dn÷10k1
4:nn mod 10k1
5:klog10(n)+1
6:print d

The new algorithm still has O(n) time complexity, but this time, it only takes O(1) space.

In line 5, we can also decrease k by 1 instead of recalculating the number of digits with log10(n).