如何在putchar仅帮助下打印整数.我想在不使用外部存储的情况下这样做.
去年在一次采访中提到了这个问题.
面对面试时的模糊要求时,表达您的假设是个好主意.
我会接受这个要求,只能putchar说它是我唯一允许调用的库函数.我还假设"没有外部存储"意味着我无法显式创建缓冲区.如果面试官同意我的假设,我会继续:
void pr_int(int n) {
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10 != 0)
pr_int(n / 10);
putchar((n % 10) + '0');
}
Run Code Online (Sandbox Code Playgroud)
如果面试官随后评论说n = -n;会失败INT_MIN,如下所述,那么我会将其重写为:
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);
}
Run Code Online (Sandbox Code Playgroud)