Imports System
Public Module NumberUtils
''' <summary>
''' Returns the N-th digit of a number counting from the right.
''' </summary>
''' <param name="number">
''' The input number.
''' </param>
''' <param name="position">
''' The digit position (1-based, from the right).
''' </param>
''' <returns>
''' The digit at the specified position.
''' </returns>
''' <exception cref="ArgumentOutOfRangeException">
''' Thrown when position is less than 1.
''' </exception>
Public Function GetDigitFromRight(number As Long, position As Integer) As Integer
If position < 1 Then
Throw New ArgumentOutOfRangeException(
NameOf(position),
"Position must be greater than 0."
)
End If
' Work with positive numbers only.
number = Math.Abs(number)
' Shift the desired digit to the ones place.
Dim divisor As Long = CLng(Math.Pow(10, position - 1))
Dim shiftedNumber As Long = number \ divisor
' Extract the last digit.
Return CInt(shiftedNumber Mod 10)
End Function
Sub Main()
Console.WriteLine(GetDigitFromRight(12345, 1))
Console.WriteLine(GetDigitFromRight(12745, 3))
Console.WriteLine(GetDigitFromRight(12345, 5))
End Sub
End Module
' run:
'
' 5
' 7
' 1
'