栈实现二进制转十进制
2019-08-03 本文已影响0人
周末的游戏之旅
二进制到十进制的转换
使用按基数乘法:
110转十进制
=0x20+1x21+1x2^2
=6
所以按此方法计算二进制转十进制可以利用栈的结构特性,将二进制按顺序入栈,然后再出栈进行计算并累加。
算法描述
Node
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkStack
{
class Node<T>
{
T data;
Node<T> next;
/// <summary>
/// 构造器
/// </summary>
public Node()
{
this.Data = default(T);
this.Next = null;
}
/// <summary>
/// 构造器
/// </summary>
/// <param name="data"></param>
public Node(T data)
{
this.Data = data;
}
public T Data { get => data; set => data = value; }
internal Node<T> Next { get => next; set => next = value; }
}
}
LinkStack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkStack
{
class LinkStack<T>
{
Node<T> top;
public LinkStack()
{
this.top = new Node<T>();
}
/// <summary>
/// 入栈
/// </summary>
/// <param name="data"></param>
public void Push(T data)
{
//新建节点
Node<T> tmp = new Node<T>(data);
//挂载节点
tmp.Next = this.top.Next;
this.top.Next = tmp;
}
/// <summary>
/// 出栈
/// </summary>
/// <returns></returns>
public T Pop()
{
if (top.Next == null) return default(T);
//保存栈顶节点
Node<T> tmp = top.Next;
//悬空栈顶节点
top.Next = top.Next.Next;
return tmp.Data;
}
/// <summary>
/// 判空
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
if (this.top.Next == null) return true;
return false;
}
/// <summary>
/// 读栈顶
/// </summary>
/// <returns></returns>
public T ReadTop()
{
return top.Next.Data;
}
}
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace LinkStack
{
class Program
{
static void Main(string[] args)
{
string s = Console.ReadLine();
LinkStack<char> ls = new LinkStack<char>();
//将字符串压栈
for (int i = 0; i < s.Length; i++)
{
ls.Push(s[i]);
}
double total = 0;
int m = 0; //指数
while (!ls.IsEmpty())
{
string c = ls.Pop()+"";
int n = Convert.ToInt32(c);
total += n * Math.Pow(2, m); //累计乘幂
++m;
Console.WriteLine(total + " / " + c + " / " + n);
}
Console.WriteLine(total);
}
}
}