How to find the digit previous to a given digit in a number with Java

1 Answer

0 votes
public 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) {
                if (number != 0) {
                    return number % 10;
                }
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int number = 8902741;
        int target = 7;

        int result = findPreviousDigit(number, target);

        if (result != -1) {
            System.out.printf("The digit before %d in %d is %d.%n", target, number, result);
        } else {
            System.out.printf("The digit %d is not found or has no previous digit in %d.%n", target, number);
        }
    }
}



/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
...