How to find the digit next to a given digit in a number with C#

1 Answer

0 votes
using System;

class DigitFinder
{
    /// <summary>
    /// Finds the digit that comes after the target digit when scanning from right to left.
    /// </summary>
    /// <param name="number">The number to search within.</param>
    /// <param name="target">The digit to find.</param>
    /// <returns>The digit that comes after the target, or -1 if not found or no next digit.</returns>
    public static int FindNextDigit(int number, int target) {
        int next = -1;

        while (number > 0) {
            int current = number % 10;
            number /= 10;

            if (current == target) {
                return next;
            }

            next = current;
        }

        return -1;
    }

    static void Main()
    {
        int number = 8902741;
        int target = 2;

        int result = FindNextDigit(number, target);

        if (result != -1) {
            Console.WriteLine($"The digit after {target} in {number} is {result}.");
        }
        else {
            Console.WriteLine($"The digit {target} is not found or has no next digit in {number}.");
        }
    }
}



/*
run:

The digit after 2 in 8902741 is 7.

*/

 



answered Oct 18, 2025 by avibootz
...