笔试面试1用C实现C库函数itoa,atoi
要求用C实现C库函数itoa或者是atoi.也就是字符串和数字的相互转换。
其实这是一个非常简单的问题。
但是有次笔试我没有理解好题意,也没有想到其实这就是一个如何将数字以字符串的方式存放。
这就是从来不刷笔试题面试题的后果啊,有时候都不知道题目究竟是想考察什么东西!
说实话,C的一些特性我不是特别熟悉,不同于C++,C++的特性我可以说是非常熟悉了,所以要用C来写对我来说也会多少有一点影响。
itoa 的实现
#include <stdio.h>
#include <conio.h>//for getch()
#include <memory.h>//for memset
void itoa(long int value,char *string){//value为一个int值,string是用来存放转换后的字符串的
int pos=0;//存放string的下标
if(value==0)
string[pos]=’0’;
else{
while(value>0){
int temp=value%10;
string[pos++]=temp+’0’;//以字符串的形式存放,将数字temp对应的字符存到string中
value=value/10;
};//这时候,数字以逆序的方式放在了string中,需在逆序一次将顺序转回来
for(int i=0;i<pos-1-i;i++){
string[i]=string[i]^string[pos-1-i];
string[pos-1-i]=string[i]^string[pos-1-i];
string[i]=string[i]^string[pos-1-i];
}
}
}
int main(){
long int num;//范围为 -2147438648~+2141438647.超过该范围会出错
int counts=0;
char str[100];
while(counts++<100){
memset(str,’\0’,strlen(str));//清空上次的结果,否则的话会影响下次结果,因为上次结果的字符串会余留在str里面
printf(“please enter the value(int):”);
scanf(“%d”,&num);
itoa(num,str);
printf(“ the string is :(string):%s\n\n”,str);
}
getch();
}
运行截图:
可以看到,最后两个结果和和一开始的不一样,最后一个是因为范围溢出了,倒数第二个是因为多了一个0在开始的地方,而我的代码没有考虑这种非法输入。
atoi的实现就更简单了
#include <stdio.h>
#include <conio.h>//for getch()
#include <memory.h>//for memset
long int atoi(const char *string){
long int sum=0;
int len=strlen(string);
int i;
long int multi=1;
for(i=len-1;i>=0;i–){
sum=sum+(string[i]-‘0’)*multi;
multi=multi*10;
}
return sum;
}
int main(){
long int num;//范围为 -2147438648~+2141438647.超过该范围会出错
int counts=0;
char str[100];
while(counts++<100){
memset(str,’\0’,strlen(str));//清空上次的结果,否则的话会影响下次结果,因为上次结果的字符串会余留在str里面
printf(“please enter the string:”);
scanf(“%s”,&str);
num=atoi(str);
printf(“ the value is :(int): %d\n\n”,num);
}
getch();
}
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:coderguang@gmail.com
2014-10-31
于GDUT
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/笔试面试1用c实现c库函数itoaatoi/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!