要求用C实现C库函数itoa或者是atoi.也就是字符串和数字的相互转换。
事实上这是一个很easy的问题。
可是有次笔试我没有理解好题意,也没有想到事实上这就是一个怎样将数字以字符串的方式存放。
这就是从来不刷笔试题面试题的后果啊。有时候都不知道题目到底是想考察什么东西!
说实话。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,'