itoa函数:将数字n转换为字符串并保存到s中 3.6例题实现

#include <stdio.h>
#include <string>
#include<stdlib.h>
using namespace std;

void reverse(char s[]);

/*itoa function,change integer into string,savd in s[];*/
char* itoa(int n);


int main()
{
	//test and I always forget add ";" in the end,becareful;
    char*s=itoa(int(-189865554));
	
	while(*s!='\0')
	{
		printf("%c",*s);
		s++;
        
	}
    
	return 0;
}

void reverse(char s[])
{
	//remember the strlen() function
	int j=0;
	int tmp;

	//the fist time  I code like this:for(int i=strlen(s)-1;i!=j;)
	for(int i=strlen(s)-1;i>j;)
	{
	
		tmp=s[j];
		s[j++]=s[i];
		s[i--]=tmp;
	}
}
char* itoa(int n)
{
	
	/* first judge the space need in s  for n*/
	bool negetive=false;
	int size=0;
	int ncopy;
	
	if(n<0)
	{
		negetive=true;
		n*=-1;
		size++;//for '-'
	}
 	ncopy=n;
	do {
		ncopy=ncopy/10;
		size++;
	} while(ncopy>0);
	//apply for space;
	char *s=(char*)malloc(sizeof(char)*(size+1));//the "size" should add 1 for '\o'
	int counter=0;
	do {
		
	    s[counter]=n%10+'0';//do remember to add '0';
		n=n/10;
		//printf("\ns[counter])
		counter++;
	} while(n>0);
	if (negetive)
	{
		s[counter++]='-';
	}
	s[counter]='\0';
	reverse(s);
	
	
	return s;
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值