All submissions

Convert Integer to String

Code

#include <stdio.h>
#include <string.h>
void print_integer_as_string(int num) {
    
    char s[128];
    memset(s,'\0',sizeof(s));
    int it=0;
    int rem;
    int sign = 0;

    if (num<0)
    {
        sign=1;
        num=-num;
    }

    if (num!=0)
    {
        while (1)
        {

            if (num==0)
            {
                break;
            }


            rem = num%10;

            num = num / 10;

            s[it++] = (char)(rem+48);

        }

        if (sign) {
            s[it++] = '-';
            s[it] = '\0';
        }

        else {
            s[it] = '\0';
        }

    }

    else {
        s[0] = '0';
        it++;
    }

    // reverse array
    for (int i=0, j=it-1; i<j; i++, j-- )
    {
        char t = s[i];
        s[i] = s[j];
        s[j] = t;
    }

    for (int i=0; s[i]!='\0'; i++)
    {
        printf("%c ",s[i]);
    }
}

int main() {
    int num;
    scanf("%d", &num);
    print_integer_as_string(num);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

123

Expected Output

1 2 3