How to get the Nth digit of a number from the right in VB.NET

2 Answers

0 votes
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
'

 



answered 1 day ago by avibootz
0 votes
Imports System

Public Module NumberUtils

	''' <summary>
	''' Returns the N-th digit from the right (1-based).
	''' </summary>
	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

		number = Math.Abs(number)

		Dim divisor As Long = 1

		For i As Integer = 1 To position - 1
			divisor *= 10
		Next

		Return CInt((number \ divisor) 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
'

 



answered 1 day ago by avibootz
...