Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any better alternatives for getting the digits of a number? (C++)

Tags:

c++

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.

like image 981
Alex Avatar asked Nov 10 '10 03:11

Alex


People also ask

How do you find the digits of a number?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How do you count numbers in C programming?

The number of digits can be calculated by using log10(num)+1, where log10() is the predefined function in math. h header file.

How do you store digits of a number in an array?

First, get the size needed to store all the digits in the number -- do a malloc of an array. Next, take the mod of the number and then divide the number by 10. Keep doing this till you exhaust all digits in the number.


1 Answers

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:

struct extracted_digits
{
    int number_of_digits;
    char digits[12];
};

You'll want to pick a suitable value for the maximum number of digits (12 here, which is enough for a 32-bit integer). Alternatively, you could return a std::array<char, 12> and encode the terminal by using an invalid value (so, after the last value, store a 10 or 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 (-).

like image 200
James McNellis Avatar answered Sep 27 '22 21:09

James McNellis