Search code examples
c++performanceintruntimedigits

Separating Digits in Int into Separate Ints


Ideally, I would like to take an int of say... 13647 and split it like so:

The first new variable (int) is the first digit. The second is the first two digits. The third is the first three digits... and so on and so on.

I'm having trouble figuring out how exactly to do this while maintaining an efficient runtime. Thank you for your help!


Solution

  • You can try the following:

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<math.h>
    
    int main()
    {
        int i = 0;
        int num = 13647;
        char inArr[20];
        itoa(num, inArr, 10);
        int numArr[strlen(inArr)];
    
        for(i = 0; i < strlen(inArr); i++) {
            numArr[i] = num/pow(10, strlen(inArr) - i - 1);
            printf("num[%d] = %d\n", i, numArr[i]); 
        }
        return 0;
    }
    

    The output will be:

    num[0] = 1
    num[1] = 13
    num[2] = 136
    num[3] = 1364
    num[4] = 13647