How can I print an integer with the help of putchar()
only. i want to do it without using external storage.
This question was asked in an interview last year.
When faced with vague requirements on an interview, it's a good idea to express your assumptions.
I would take the requirement about only being able to use putchar
to mean that it is the only library function I am allowed to call. I would furthermore assume that "no external storage" meant that I could not explicitly create a buffer. If the interviewer agreed with my assumptions, I would proceed with:
void pr_int(int n) {
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10 != 0)
pr_int(n / 10);
putchar((n % 10) + '0');
}
If the interviewer then commented that n = -n;
would fail for INT_MIN
, as noted below, then I would rewrite it as:
void pr_uint(unsigned int n) {
if (n / 10 != 0)
pr_uint(n / 10);
putchar((n % 10) + '0');
}
void pr_int(int n) {
if (n < 0) {
putchar('-');
n = -n;
}
pr_uint((unsigned int) n);
}