Home > Software design >  C - How to split the digits of a number into an array?
C - How to split the digits of a number into an array?

Time:10-26

If I have a number (long), how can I split its digits into an array?

Example: 4003607001000014 -> [4, 0, 0, 3, 6, 0, 7, 0, 0, 1, 0, 0, 0, 0, 1, 4].

I tried using modulo (n % (10 * i)), where i starts at 1 and its value increases by a multiple of 10 each iteration of a for loop. Then adding the result to the array from n to 0, but this way, any zeros are ignored.

CodePudding user response:

Try dividing the number by 10 each iteration, this is more straightforward than modulo by increasing powers of 10:

unsigned char digits[BIG_ENOUGH];
unsigned long number;
unsigned i = 0;
while (number) {
    digits[i  ] = number;
    number /= 10;
}

If you need digits[0] to store the most significant digit instead of the least significant digit, reverse the array afterwards:

for (unsigned low = 0, high = digits-1; low < high; low  , high--) {
    unsigned char tmp = digits[low];
    digits[low] = digits[high];
    digits[high] = tmp;
}
  •  Tags:  
  • c
  • Related