Convert Integer to String

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    // Your logic here

    if (num == 0) {
        printf("0");
        return;
    }

    //check the sign
    int num_ref = num;
    int sign = 1;
    if(num < 0) {
        sign = -1;
        // convert number to positive
        num_ref *= -1;
    }

    char buff[25];
    // buff[63] = '\0';
    int idx = 0;
    while(num_ref > 0) {
        int digit = num_ref % 10;
        num_ref = num_ref / 10;
        char digit_str = digit + '0';
        buff[idx++] = digit_str;
    }

    // print the value
    idx--;
    if(sign == -1) {
        printf("- ");
    }
    while(idx >= 0){
        printf("%c ", buff[idx--]);
    }
}

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