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

1 Answer

0 votes
#include <iostream>

// Finds the digit that comes before the target digit when scanning from right to left.

int findPreviousDigit(int number, int target) {
    int previous = -1;
    int current;

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

        if (current == target) {
            if (number != 0) {
                return number % 10;
            }
        }

        previous = current;
    }

    return -1;
}

int main() {
    int number = 8902741;
    int target = 7;

    int result = findPreviousDigit(number, target);

    if (result != -1) {
        std::cout << "The digit before " << target << " in " << number << " is " << result << ".\n";
    } else {
        std::cout << "The digit " << target << " is not found or has no previous digit in " << number << ".\n";
    }
}


/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered Oct 20, 2025 by avibootz
edited Oct 21, 2025 by avibootz
...