VB.Net数据结构系列 第3章 栈和队列 3.1 栈

1、进制的计算,要换算的数字N,进制D(不超过十六进制)。

步骤一:N除以D,商为Q,余数为R,

根据ASCII表,R如果小于10,那么直接加上48,然后转为Char类型,对应0-9;R如果大于等于10,那么减去10,加上65,(或者直接加上55),然后转为Char类型,对应A-F。转换后的字符存入栈(Push);

步骤二:N=Q,继续执行步骤一,直到商为0

步骤三:由于栈是先进后出,按照此原理,取出栈内的字符(Pop),就可以组成转换后的字符串。

Code3-1

Stack.vb:

Public Class Stack

    Private stackarray() As Object
    Private Const defaultCapacity = 10
    Private size As Integer

    Public ReadOnly Property Count As Integer
        Get
            Return size
        End Get
    End Property

    Sub New()
        stackarray = New Object(defaultCapacity - 1) {}
        size = 0
    End Sub

    Sub New(ByVal initialCapacity As Integer)
        If initialCapacity < 0 Then
            Throw New ArgumentOutOfRangeException("栈空间不能小于零!")
        End If
        If initialCapacity < defaultCapacity Then
            initialCapacity = defaultCapacity
        End If
        stackarray = New Object(initialCapacity - 1) {}
        size = 0
    End Sub

    Public Function Pop() As Object
        If size = 0 Then
            Throw New InvalidOperationException("栈下溢,栈内已无数据!")
        End If
        Dim obj2 As Object
        size = size - 1
        obj2 = stackarray(size)
        stackarray(size) = Nothing
        Return obj2
    End Function

    Public Sub Push(ByVal obj As Object)
        If size = stackarray.Length Then
            Dim destinationArray() As Object = New Object(stackarray.Length * 2) {}
            Array.Copy(stackarray, 0, destinationArray, 0, stackarray.Length)
            stackarray = destinationArray
        End If
        stackarray(size) = obj
        size += 1
    End Sub

End Class

Module1.vb:

Module Module1

    Sub Main()
        Console.WriteLine(DecConvert(27635, 16))
        Console.WriteLine(DecConvert(27635, 8))
        Console.WriteLine(DecConvert(27635, 2))
        Console.ReadKey()
    End Sub

    Private Function DecConvert(ByVal N As Integer, ByVal D As Integer) As String
        If (D <> 16) And (D <> 8) And (D <> 2) Then
            Throw New ArgumentOutOfRangeException("D", "支支持十进制转二进制、八进制、十六进制!")
        End If
        Dim stack As New Stack()
        Do
            Dim residue As Integer
            residue = N Mod D
            Dim c As Char
            c = IIf(residue < 10, Chr(residue + 48), Chr(residue + 55))
            stack.Push(c)
            N = N \ D
        Loop While N <> 0
        Dim s As String = ""
        Do While stack.Count > 0
            s &= stack.Pop.ToString
        Loop
        Return s
    End Function

End Module

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值