117. Convert Integer to String

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

void print_integer_as_string(int num) {
    // handle special case for zero
    if (num == 0) {
        printf("0");
        return;
    }

    // handle negative sign
    if (num < 0) {
        printf("- ");
        num = -num;
    }

    // find the highest power of ten
    int power = 1;
    while (power <= num) {
        power *= 10;
    }

    // print the digits
    while (power > 1) {
        power /= 10;
        printf("%u ", num / power);
        num %= power;
    }
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote