0

I was wondering how is it possible to get the digital elements of an integer so that I could display an array such as [1][7] coming from the number 17 for instance. I found this solution here for counting the digits and now I need to fit the digits composing the integer into an array and so wants to retrieve the value of each of them

int A = 17;
int table[lenght_of_A];
A 'operation_to_fit_A_in' table;
Community
  • 1
  • 1
Yvain
  • 29
  • 10

3 Answers3

1

In C++ I would do it like this. Then there is no need to count the digits beforehand:

#include <list>

std::list<int> digits;
// Slightly adapted algorithm from sharptooth: this one yields a zero if 
// the value was 0. (sharptooth's wouldn't yield the digit 0 if a zero was 
// being analyzed.)
do {
    digits.push_front( value%10 );
    value /= 10;
} while( value!=0 );

digits now contains a list of the individual digits and can be displayed in any form you like.

emvee
  • 4,371
  • 23
  • 23
  • I would prefer a vector as it tends to be faster. – Neil Kirk Mar 06 '15 at 11:03
  • `vector` only supports `.push_back()`, which will lead to re-allocations when the vector grows. Inserting at the front of a vector is (very) expensive; all following members need to be shifted 'upwards'. When using `.push_back()` then either you have to remember to reverse the vector or, alternatively, iterate from `.rbegin()` to `.rend()`. So I'm not sure that `vector` would always be guaranteed to be faster. Maybe if the elements are pre-allocated (but then you need to analyze the number, knowing how many digits it contains, which will also cost a bit of time). – emvee Mar 06 '15 at 11:09
  • I didn't notice you were pushing front! However, pushing a few ints up is cheaper than the extra allocations used by a list. You could also push back and then reverse the vector. – Neil Kirk Mar 06 '15 at 11:22
0

The idea is that you run a loop (pseudocode):

while( value != 0 ) {
    nextDigitValue = value % 10; // this is "modulo 10"
    nextDigitChar = '0' + nextDigitValue;
    value = value / 10; // this lets you proceed to next digit
}
sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

thanks for the help. Finally InI got it working.

void Getint(int A; int* array)
{
    if (A < 10)
        array[0] = A;
        array[1] = 0;
    if (A >= 10 &&  A < 100)
        array[0] = A / 10;
        array[1] = A % 10;
}
Yvain
  • 29
  • 10