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

1 Answer

0 votes
def find_next_digit(number: int, target: int) -> int:
    """
    Finds the digit that comes after 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 after the target, or -1 if not found or no next digit.
    """
    next_digit = -1

    while number > 0:
        current_digit = number % 10
        number //= 10

        if current_digit == target:
            return next_digit

        next_digit = current_digit

    return -1



number = 8902741
target = 2

result = find_next_digit(number, target)

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