实现一个函数itoa(int n, char s[]),将整数n这个数字转换为对应的字符串,保存到s中。
#include <stdio.h>
void reverse(char *left, char *right)
{
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
void my_itoa(int n, char s[])
{
char *start;
char *end;
if (n < 0)
{
*s = ‘-‘;
n = -n;
s++;
}
start = s;
while (n)
{
*s = (n % 10) + ‘0‘;
s++;
n /= 10;
}
*s = ‘\0‘;
end = s - 1;
reverse(start, end);
}
int main()
{
int num = -1234;
char arr[10];
my_itoa(num, arr);
printf("%s\n", arr);
return 0;
}
时间: 2024-11-07 17:57:02