Krzysiek Krzysiek - 5 days ago 4x
C++ Question

splitting a number and storing in int array

Is there a way to split a number and store digits in an int array?

I am looking for a way to remove some digits from a number (for a divisible algorithm proof).

for example, if I have a number 12345, I need to perform this operation:

1234 - 5 = 1229

Is there a way to do this?


Use n % 10 to get the last digit and n / 10 to get the others. For example, 5=12345%10, 1234=12345/10.

Convert integer to array:

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

In general, vectors are preferred in C++, especially in this case since you probably don't know in advance the number of digits.

int n = 123456;
vector<int> v;
for(; n; n/=10)
  v.push_back( n%10 );

Then v contains {6,5,4,3,2,1}. You may optionally use std::reverse to reverse it.