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

1 Answer

0 votes
using System;

class DigitFinder
{
    // Finds the digit that comes before the target digit when scanning from right to left.
    public static int FindPreviousDigit(int number, int target) {
        while (number > 0) {
            int current = number % 10;
            number /= 10;

            if (current == target) {
                return number > 0 ? number % 10 : -1;
            }
        }

        return -1;
    }

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

        int result = FindPreviousDigit(number, target);

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



/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered Oct 21, 2025 by avibootz
...