笔试面试题11--整数与字符串转化

面试例题1:怎样将整数转化成字符串数,并且不用函数itoa?

# if 0
//整数转化为字符串,不使用itoa()
# include <stdio.h>

int main()
{
    int num = 12345;
    int i = 0;

    char temp[7],str[7];

    while(num)
    {
        temp[i] = num%10 + '0';//转化为字符
        i++;
        num = num/10;
    }
    temp[i] = '\0';//添加字符串末尾标识符

    printf("temp = %s\n",temp);
    i = i - 1;
    printf("temp = %d\n",i);

    while(i >= 0)//逆序输出字符串
    {
        str[j] = temp[i];
        j++;
        i--;
    }
    str[j] = '\0';
    printf("string = %s\n",str);
    return 0;
}
# endif

面试例题2:编程实现字符串数转化成整数的办法。

# if 1
//字符串转化为整数,不使用atoi()
# include <stdio.h>

int main()
{
    int num = 12345;
    int i = 0;
    int sum = 0;
    char temp[7] = {'1','2','3','4','5','\0'};

    while(temp[i])
    {
        sum = sum * 10 + (temp[i] - '0');
        i++;
    }
    printf("sum = %d\n",sum);
    return 0;
}
# endif

你可能感兴趣的:(面试题)