How to get the Nth digit of a number from the right in C#

1 Answer

0 votes
using System;

namespace DigitExample
{
    internal static class Program
    {
        /// <summary>
        /// Returns the N-th digit of a number counting from the right.
        ///
        /// Examples:
        /// GetDigit(12945, 1) => 5
        /// GetDigit(12945, 2) => 4
        /// GetDigit(12945, 3) => 9
        /// </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>
        private static int GetDigit(long number, int position)
        {
            if (position < 1) {
                throw new ArgumentOutOfRangeException(
                    nameof(position),
                    "Position must be greater than 0.");
            }

            // Handle negative numbers.
            number = Math.Abs(number);

            // Calculate 10^(position - 1) using integer arithmetic.
            long divisor = 1;

            for (int i = 1; i < position; i++) {
                divisor *= 10;
            }

            // Shift the desired digit to the ones place
            // and extract it.
            return (int)((number / divisor) % 10);
        }

        private static void Main()
        {
            long number = 12945;

            Console.WriteLine($"Number: {number}");
            Console.WriteLine($"1st digit from right: {GetDigit(number, 1)}");
            Console.WriteLine($"3rd digit from right: {GetDigit(number, 3)}");
            Console.WriteLine($"5th digit from right: {GetDigit(number, 5)}");
        }
    }
}


/*
run:

Number: 12945
1st digit from right: 5
3rd digit from right: 9
5th digit from right: 1

*/

 



answered Oct 13 by avibootz
...