I know that you can get the digits of a number using modulus and division. The following is how I’ve done it in the past: (Psuedocode so as to make students reading this do some work for their homework assignment):
int pointer getDigits(int number)
initialize int pointer to array of some size
initialize int i to zero
while number is greater than zero
store result of number mod 10 in array at index i
divide number by 10 and store result in number
increment i
return int pointer
Anyway, I was wondering if there is a better, more efficient way to accomplish this task? If not, is there any alternative methods for this task, avoiding the use of strings? C-style or otherwise?
Thanks. I ask because I’m going to be wanting to do this in a personal project of mine, and I would like to do it as efficiently as possible.
Any help and/or insight is greatly appreciated.
The time it takes to extract the digits will be dwarfed by the time required to dynamically allocate the array. Consider returning the result in a struct:
You’ll want to pick a suitable value for the maximum number of digits (
12here, which is enough for a 32-bit integer). Alternatively, you could return astd::array<char, 12>and encode the terminal by using an invalid value (so, after the last value, store a10or something else that isn’t a digit).Depending on whether you want to handle negative values, you’ll also have to decide how to report the unary minus (
-).