Convert Integer to String

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    // Your logic here
    char buffer[12];   // Enough for int32: -2147483648
    int i = 0;

    // Handle zero explicitly
    if (num == 0) {
        putchar('0');
        putchar('\n');
        return;
    }

    // Handle negative numbers
    if (num < 0) {
        putchar('-');
        putchar(' ');
        num = -num;
    }

    // Convert digits to characters (reverse order)
    while (num > 0) {
        buffer[i++] = (num % 10) + '0';
        num /= 10;
    }

    // Print digits in correct order with spaces
    for (int j = i - 1; j >= 0; j--) {
        putchar(buffer[j]);
        if (j > 0) {
            putchar(' ');
        }
    }

    putchar('\n');
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

123

Expected Output

1 2 3