【面试题】itoa实现

#include <iostream>
#include <stack>
using namespace std;

char *itoa_bxy(int num, char *a,int radix)
{
	char *tmp = a;
	int flag = num;
	//如果是负数,采用相反数来计算
	if(flag < 0)
	{
		num = -num;
	}
	//从低位开始遍历数字,入栈。
	stack<char> s;
	while(num != 0)
	{
		char x = num % radix+'0';
		s.push(x);
		num = num / radix;
	}
	//如果是负数,符号入栈
	if(flag < 0)
	{
		s.push('-');
	}
	//数组的下标
	int c=0;
	//出栈,装入参数中,返回给主调函数
	while(!s.empty())
	{
		a[c++] = s.top();
		s.pop();
	}
	//加结尾标记
	a[c] = '\0';
	return tmp;
}

void main()
{
	int num = -124442;
	char a[10];
	char *x = itoa_bxy(num,a,10);
	cout << x <<endl;
}



   

你可能感兴趣的:(C++,c,面试,include)