最近参加面试发现这两个函数考试的比较多,就简单总结一下:
void int2str(int n, char *str)
{
char buf[10] = "";
int i = 0;
int len = 0;
int temp = n < 0 ? -n: n; // temp为n的绝对值
if (str == NULL)
{
return;
}
while(temp)
{
buf[i++] = (temp % 10) + '0'; //把temp的每一位上的数存入buf
temp = temp / 10;
}
len = n < 0 ? ++i: i; //如果n是负数,则多需要一位来存储负号
str[i] = 0; //末尾是结束符0
while(1)
{
i--;
if (buf[len-i-1] ==0)
{
break;
}
str[i] = buf[len-i-1]; //把buf数组里的字符拷到字符串
}
if (i == 0 )
{
str[i] = '-'; //如果是负数,添加一个负号
}
}
int str2int(const char *str)
{
int temp = 0;
const char *ptr = str; //ptr保存str字符串开头
if (*str == '-' || *str == '+') //如果第一个字符是正负号,则移到下一个字符
{
str++;
}
while(*str != 0)
{
if ((*str < '0') || (*str > '9')) //如果当前字符不是数字则退出循环
{
break;
}
temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值
str++; //移到下一个字符
}
if (*ptr == '-') //如果字符串是以“-”开头,则转换成其相反数
{
temp = -temp;
}
return temp;
}