Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

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 3 days ago 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 3 days ago by avibootz
...