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

I know that you can get the digits of a number using module and division. The following is how I did it in the past: (Psuedocode so that students reading this do some work for their homework):

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, are there alternative methods for this task, avoiding the use of strings? C-style or otherwise?

Thank. I ask because I am going to do this in my personal project, and I would like to do it as efficiently as possible.

Any help and / or understanding is greatly appreciated.

+5
source share
7 answers

, , , . struct:

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

(12 , 32- ). std::array<char, 12> , ( 10 - , ).

, , , (-).

+3

, 2, .

+3

" ", , , , .

, . , . , , C - ++, ++. , , .

" " , , :

typedef struct {
    int ival;
    char sval[sizeof("-2147483648")]; // enough for 32-bits
    int dirtyS;
} tIntStr;

( ), .

, :

inline void intstrSetI (tIntStr *is, int ival) {
    is->ival = i;
    is->dirtyS = 1;
}
inline char *intstrGetS (tIntStr *is) {
    if (is->dirtyS) {
        sprintf (is->sval, "%d", is->ival);
        is->dirtyS = 0;
    }
    return is->sval;
}

, , :

tIntStr is;
intstrSetI (&is, 42);

, :

printf ("%s\n" intstrGetS(&is));
fprintf (logFile, "%s\n" intstrGetS(&is));

, ( fprintf printf, ).

, SQL . , . , insert/update , select lower(non_lowercased_last_name). , ( ) .

, set-int/use-string/set-int/use-string.... set-int/use-string/use-string/use-string/use-string..., .

, , /.

, ( , ), , ( ) .


: , . , , , ( , , ).

, itoa, , , sprintf("%d"), . , , , ! , ( ).

+1

. , , itoa - , ++, (, AAM, ). ( ), . ITOA ( , , CPU).

+1

, , . Intel FPU BCD. , , , , ST (0) BCD . FBSTP.

+1

, base-100 , "" 00 - 99. %100 , , . , 200 10. , L1 (, , efficientcy ). , , "0128".

+1

1+int(log10(abs(a)+1))+(a<0);.

You will not use strings, but you will go through floating points and log functions. If on your platform there is any type of FP accelerator (each PC or similar) that will not matter much and will beat any algorithm based on freezing (this means that it is more than iterative division by ten and count)

0
source

All Articles