C#栈的实现(数制转换)

using System ; public class Stacks { private object [] _array; //存放元素的数组; private const int _defaultCapacity=10; //默认空间; private int _size; //指示元素个数; public Stacks () { this._array=new object[_defaultCapacity] ; this._size=0; } public Stacks(int initalCapacity) { if(initalCapacity <0) { throw new ArgumentOutOfRangeException("栈空间不能小于0!"); } if(initalCapacity <_defaultCapacity ) { initalCapacity =_defaultCapacity ; } this._array=new object[initalCapacity] ; //分配栈空间; this._size=0; } //出栈; public object Pop() { if(this._size==0) { throw new InvalidOperationException("栈下溢,栈内已无数据!"); } object obj2=this._array[--this._size]; //取出栈顶元素; this._array[this._size]=null; //删除栈顶元素; return obj2; } //进栈; public void Push(object obj) { if(this._size==this._array.Length) { //如果栈空间已满,则将原来空间扩展为原来的2倍; object[]destinationArray=new object[2*this._array.Length]; Array.Copy(this._array,0,destinationArray ,0,this._size); this._array=destinationArray; } } public int Count { get {return this._size;} } } class App { static string DecConvert(int N,int D) { if(D<2||D>16) { throw new ArgumentOutOfRangeException("D","只支持将十进制数据转换为二进制至16进制!"); } Stacks stack=new Stacks (); do { int residue=N%D;//取余; char c=(residue <10)?(char)(residue+48):(char)(residue+55); stack.Push(c); //进栈; } while ((N=N/D)!=0); string s=string.Empty; while (stack.Count>0) { s+=stack.Pop().ToString(); } return s; } static void Main() { Console.WriteLine(DecConvert(27635,16)); Console.WriteLine(DecConvert(27635,8)); Console.WriteLine(DecConvert(27635,2)); } }

你可能感兴趣的:(object,String,C#,System,Class,扩展)