static void Main(string[] args) { Program main = new Program(); main.testStack1(); Console.WriteLine(main.testStack2(20, 2)); } private void testStack1() { Stack<int> stack1 = new Stack<int>(); stack1.Push(1); stack1.Push(2); stack1.Push(3); stack1.Push(4); while (true) { if (stack1.Count > 0) { Console.WriteLine(stack1.Pop()); } else { break; } } } /// <summary> /// 利用栈进行进制转换 /// </summary> /// <param name="N">10进制的数字</param> /// <param name="D">进制</param> /// <returns>转换后的字符串</returns> public string testStack2(int N, int D) { if (D < 2 || D > 16) { throw new ArgumentOutOfRangeException("D", "只支持2、8、10、16进制的转换!"); } Stack<char> stack = new Stack<char>(); do { //取余 int Residue = N % D; char c = (Residue < 10) ? (char)(Residue + 48) : (char)(Residue + 55); stack.Push(c); } while ((N = N / D) != 0);//当商为0时代表运算结束 string s = string.Empty; while (stack.Count > 0) { //弹出所有的元素 s += stack.Pop().ToString(); } return s; }
效果: