How to get the Nth digit of a number from the right in Python

2 Answers

0 votes
def get_digit_from_right(number: int, position: int) -> int:
    """
    Return the N-th digit of a number counting from the right.

    Examples:
        get_digit_from_right(12345, 1) -> 5
        get_digit_from_right(12345, 2) -> 4
        get_digit_from_right(12845, 3) -> 8

    Args:
        number: The input integer.
        position: The digit position (1-based, from the right).

    Returns:
        The digit at the specified position.

    Raises:
        ValueError: If position is less than 1.
    """
    if position < 1:
        raise ValueError("Position must be greater than 0.")

    # Work with positive numbers only.
    number = abs(number)

    # Shift the desired digit to the ones place.
    number //= 10 ** (position - 1)

    # Extract the last digit.
    return number % 10


# Example usage
print(get_digit_from_right(12345, 1)) 
print(get_digit_from_right(12845, 3)) 
print(get_digit_from_right(12345, 5)) 


'''
run:

5
8
1

'''

 



answered Oct 13 by avibootz
0 votes
def get_digit_from_right(number: int, position: int) -> int:
    """Return the N-th digit from the right (1-based)."""
    if position < 1:
        raise ValueError("Position must be greater than 0.")

    return abs(number) // (10 ** (position - 1)) % 10


# Example usage
print(get_digit_from_right(12345, 1)) 
print(get_digit_from_right(12845, 3)) 
print(get_digit_from_right(12345, 5)) 


'''
run:

5
8
1

'''

 



answered Oct 13 by avibootz
...