可打印的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 a interview last year.
推荐答案
当面对上接受记者采访时含糊的要求,这是一个好主意,当然preSS你的假设。
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屋!