Refactor the code to improve the use of memory for each digit. TODO: clean doc