作为@Potatoswatter简洁的cmets,使用标准itoa()就可以了。
至于什么是最快的:最好地描述候选解决方案。在一个平台上效果最好的方法在另一个平台上可能会有所不同。
以下是另一种实现。 Flowing 是一种紧密的递归解决方案,不需要反转其结果。它适用于所有int:[INT_MIN, INT_MAX],因为它适用于int 的负侧,其大小与正侧相同或更大。
static char *itoa10_helper(int n, char *s) {
if (n <= -10) {
s = itoa10_helper(n / 10, s);
}
*s = (char) ('0' - n % 10);
return ++s;
}
char* itoa10(int n, char *s) {
if (n < 0) {
*s = '-';
*itoa10_helper(n, s+1) = 0;
} else {
*itoa10_helper(-n, s) = 0;
}
return s;
}
#include <limits.h>
#include <stdio.h>
#define INT_MAX_SIZE (sizeof (int)*CHAR_BIT/3 + 3)
int main(void) {
char buf[INT_MAX_SIZE];
puts(itoa10(0, buf));
puts(itoa10(123, buf));
puts(itoa10(INT_MAX, buf));
puts(itoa10(INT_MIN, buf));
return 0;
}
一个快速的解决方案,它在提供的缓冲区中返回一个指针somewhere,如下所示:
#include <stdbool.h>
char* itoa10f(int n, char *buf) {
char *s = buf + INT_MAX_SIZE - 1;
*s = '\0';
bool isnegative = n < 0;
if (!isnegative) {
n = -n;
}
do {
*(--s) = (char) ('0' - n % 10);
} while (n /= 10);
if (isnegative) {
*(--s) = '-';
}
return s;
}