kantor
kantor

Reputation: 239

Convert integer to array

I would like to convert an integer into an array, so that it looks like the following:

int number = 123456 ;
int array[7] ;

with the result:

array[0] = 1 
array[1] = 2
...
array[6] = 6

Upvotes: 23

Views: 132126

Answers (13)

Muhammad Saad
Muhammad Saad

Reputation: 1

To convert an integer to array, you can do the steps below:

  • Get the total number of digits in a number to which we want to convert to array.For this purpose, we will use count_digits() function which will return total no of digits after ignoring leading zeros.
digits = count_digits(n);
  • Now we will dynamically allocate memory for our resulting array, just like
int* arr = new int[count_digits(n)]
  • After allocating memory, we will populate the array using the for loop below
int digits = count_digits(num);
for (int i = digits; i > 0; i--){
    arr[i-1] = num % 10;
    num = num / 10;
}

After performing the steps above, we will be able to convert an integer to array. Remember, num is the number that we want to convert into array and digits is the variable which gives us the number of digits in a given number ignoring leading zeros.

Upvotes: 0

No Name
No Name

Reputation: 11

#include <cmath>
#include <vector>    

std::vector<int> vec;
for (int i = log10(input); i >= 0; i--)
{
  vec.push_back(input / int(std::pow(10, i)) % 10);
}

Might be a good approach, I think

Upvotes: 1

Orhun Yeldan
Orhun Yeldan

Reputation: 71

Here what I came up with, the integerToArray function returns a vector that is converted from the integer value. you can test it with the main function as well:

#include <iostream>
#include <vector>
using namespace std;

vector <int> integerToArray(int x)
{
    vector <int> resultArray;
    while (true)
    {
    resultArray.insert(resultArray.begin(), x%10);
    x /= 10;
    if(x == 0)
        return resultArray;
    }
}

int main()
{
    vector <int> temp = integerToArray(1234567);
    for (auto const &element : temp)
        cout << element << " " ;
    return 0;
}

//outputs 1 2 3 4 5 6 7 

Upvotes: 7

smokenstein
smokenstein

Reputation: 45

If you wanted to turn it into a string then it would be really easy, just do what everyone else is saying about using the % operator:

Let's say num = 123, we can do this:

string str;
while (num > 0)
{
   str = (num % 10) + str;  //put last digit and put it into the beginning of the string
   num = num /10;  //strip out the last digit
}

Now you can use str as an array of chars. Doing this with an array is a hassle because putting things in the beginning of an array requires you to shift everything else. What we can do is, instead of putting each digit into a string, we can put it into a stack. It will put it in a backwards order like this: 3 2 1. Then we can pop off the top number one by one and put that into an array in the correct order. You array will look like this: 1 2 3. I will leave the implementation to you since this is homework.

@Broam has a good solution, but like he stated, it's for working backwards. I think the OP or whoever comes looking into this thread will want it forwards and that's why I'm posting this. If you have a better solution, please reply, I'm interested as well.

Upvotes: 0

Dominic.wig
Dominic.wig

Reputation: 314

if this is really homework then show it your teacher - just for fun ;-)

CAUTION! very poor performance, clumsy way to reach the effect you expect and generally don't do this at home(work) ;-)

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

typedef std::vector< int > ints_t;

struct digit2int
{
    int operator()( const char chr ) const
    {
        const int result = chr - '0';
        return result;
    }
};

void foo( const int number, ints_t* result )
{
    std::ostringstream os;
    os << number;
    const std::string& numberStr = os.str();
    std::transform(
        numberStr.begin(),
        numberStr.end(),
        std::back_inserter( *result ),
        digit2int() );
}

int main()
{
    ints_t array;
    foo( 123456, &array );
    std::copy(
        array.begin(),
        array.end(),
        std::ostream_iterator< int >( std::cout, "\n" ) );
}

Upvotes: 0

Peter Olsson
Peter Olsson

Reputation: 1322

See SO question Language showdown: Convert string of digits to array of integers? for a C/C++ version (as well as other languages).

Upvotes: 0

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247919

You can't simply "convert" it. The integer is not represented in software in decimal notation. So the individual digits you want don't exist. They have to be computed.

So, given an arbitrary number, how can you determine the number of ones?

We could divide by ten, and then take the remainder: For 123, the division would give 12, and then there's a remainder of 3. So we have 3 ones. The 12 tells us what we have past the ones, so it can be our input for the next iteration. We take that, divide by 10, and get 1, and a remainder of 2. So we have 2 in the tens place, and 1 left to work with for the hundreds. Divide that by 10, which gives us zero, and a remainder of 1. So we get 1 in the hundreds place, 2 in the tens place, and 3 in the ones place. And we're done, as the last division returned zero.

Upvotes: 0

philsquared
philsquared

Reputation: 22493

Take the log10 of the number to get the number of digits. Put that in, say pos, then, in a loop, take the modulo of 10 (n % 10), put the result in the array at position pos. Decrement pos and divide the number by 10. Repeat until pos == 0

What did you want to do with the sign if it's negative?

Upvotes: 2

Broam
Broam

Reputation: 4648

Perhaps a better solution is to work backwards:

123456 % 10 = 6

123456 / 10 = 12345

12345 % 10 = 5

12345 / 10 = 1234

Upvotes: 31

user224003
user224003

Reputation: 217

just use modular arithmetic:

int array[6];
int number = 123456;
for (int i = 5; i >= 0; i--) {
    array[i] = number % 10;
    number /= 10;
}

Upvotes: 18

Drew Dormann
Drew Dormann

Reputation: 63755

You can use modulus to determine the last digit.

And you can use division to move another digit to the last digit's place.

Upvotes: 0

avakar
avakar

Reputation: 32635

You can extract the last digit of the number this way:

int digit = number % 10;
number /= 10;

Note that you should also check whether number is positive. Other values require additional handling.

Upvotes: 6

Andres
Andres

Reputation: 3414

The easiest way I can imagine now is:

char array[40];
int number = 123456;

memset(array, 0x00, sizeof(array));

sprintf(array, "%d", number);

Additionally you can convert each digit to int just subtracting the char value by 0x30.

EDIT: If this is a homework, your teacher you probably ask you to write the program using % operator though (example 12 % 10 = 2). If this is the case, good homework ;-)

Upvotes: 0

Related Questions