上一篇实现字符串转化成整数,这里实现整数转化成字符串。
实现方法IntToStr,代码:
/// <summary>
/// 将数字转化为字符串
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static string IntToStr(int value)
{
string str = "";
Stack<char> stack = new Stack<char>();
bool isNagetive = false;
int digit = 0;
char c;
//负整数
if (value<0)
{
isNagetive = true;
while (value <= -10)
{
digit = -(value % 10); //求个位数
c = (char)('0' + digit); //求digit对应的char
stack.Push(c); //压入栈
value = value / 10; //除以10的整数部分
}
if (value!=0) //最后一位
{
c = (char)('0' + -value);
stack.Push(c);
}
}
//0
else if (value == 0)
{
c = (char)('0');
str += c;
return str;
}
//正整数
else
{
while (value >= 10)
{
digit = value % 10;
c = (char)('0' + digit);
stack.Push(c);
value = value / 10;
}
if (value != 0)
{
c = (char)('0' + value);
stack.Push(c);
}
}
if (isNagetive)
{
stack.Push('-');
}
while (stack.Count>0)
{
str += stack.Pop();
}
return str;
}