Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting integer into array of digits [closed]

Tags:

c++

c

I need to convert two integers into two arrays of digits, so for example 544 would become arr[0] = 5, arr[1] = 4, arr[2] = 4.

I have found some algorithms doing this, but they create new array, and return this. I would have to allocate this memory for two arrays, so I wanna pass two integers by reference and do this on them directly.

I guess I can do this, because these integers are in fact template types, so they should be changeable. That's why I added C++ tag here.

like image 972
user2252786 Avatar asked Apr 13 '13 12:04

user2252786


2 Answers

Just using something like this:

int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array

while (n) { // loop till there's nothing left
    a[i++] = n % 10; // assign the last digit
    n /= 10; // "right shift" the number
}

Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of i as well as the increment/decrement based on how you'd like to determine to length of the value.


(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:

{
    char *df = a, *dr = a + i - 1;
    int j = i >> 1;

    while (j--)
    {
        char di = *df, dj = *dr;
        *df++ = dj, *dr-- = di; /* (exchange) */
    }
}
like image 116
Mario Avatar answered Oct 15 '22 17:10

Mario


A simple solution is:

int i = 12312278;

std::vector<int> digits;

while (i)
{
    digits.push_back(i % 10);

    i /= 10;
}

std::reverse(digits.begin(), digits.end());

or, string based ( i >= 0 )

for (auto x : to_string(i))
    digits.push_back(x-'0');
like image 32
masoud Avatar answered Oct 15 '22 18:10

masoud