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

1 Answer

0 votes
def find_previous_digit(number: int, target: int) -> int:
    """
    Finds the digit that comes before the target digit when scanning from right to left.

    Args:
        number (int): The number to search within.
        target (int): The digit to find.

    Returns:
        int: The digit that comes before the target, or -1 if not found or no previous digit.
    """
    while number > 0:
        current = number % 10
        number //= 10

        if current == target:
            return number % 10 if number > 0 else -1

    return -1


number = 8902741
target = 7

result = find_previous_digit(number, target)

if result != -1:
    print(f"The digit before {target} in {number} is {result}.")
else:
    print(f"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 by avibootz
...