How to increment an integer represented as an integer list of digits by one in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class Program
    Private Shared Function IncrementByOne(ByVal digits As List(Of Integer)) As List(Of Integer)
        Dim carry As Integer = 1

		For i As Integer = digits.Count - 1 To 0 step -1
            digits(i) += carry

            If digits(i) = 10 Then
                digits(i) = 0
                carry = 1
            Else
                carry = 0
                Exit For
            End If
        Next

        If carry = 1 Then
            digits.Insert(0, 1)
        End If

        Return digits
    End Function

    Public Shared Sub Main()
        Dim digits As List(Of Integer) = New List(Of Integer) From {
            9,
            9,
            9
        }
        IncrementByOne(digits)
        Console.Write("Result: ")

        For Each digit As Integer In digits
            Console.Write(digit & " ")
        Next

        Console.WriteLine()
    End Sub
End Class



' run:
'
' Result: 1 0 0 0 
'

 



answered Jul 2 by avibootz
...