Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,561 questions

56,774 answers

573 users

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 2 days ago by avibootz
...