putchar()可以打印整数吗? [英] Can putchar() print an integer?
问题描述
如何仅在putchar()
的帮助下打印整数.我想在不使用外部存储的情况下做到这一点.
去年的一次采访中问了这个问题.
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.
我只能使用putchar
来表示它是唯一允许我调用的库函数.我还要进一步假设没有外部存储"意味着我无法显式创建缓冲区.如果访问者同意我的假设,我将继续:
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');
}
如果面试官随后评论说n = -n;
对于INT_MIN
失败,如下所述,那么我将其重写为:
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);
}
这篇关于putchar()可以打印整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!