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

1 Answer

0 votes
#include <iostream>
#include <stdexcept>
#include <cmath>

/**
 * @brief Returns the N-th digit of a number counting from the right.
 *
 * Example:
 * number = 12345
 * position = 1 -> 5
 * position = 2 -> 4
 * position = 3 -> 3
 *
 * @param number   The input number.
 * @param position The digit position (1-based, from the right).
 * @return int     The digit at the specified position.
 *
 * @throws std::invalid_argument if position < 1.
 */
int getDigitFromRight(long long number, int position)
{
    if (position < 1) {
        throw std::invalid_argument("Position must be greater than 0.");
    }

    // Work with positive numbers only.
    number = std::llabs(number);

    // Shift the desired digit to the ones place.
    for (int i = 1; i < position; ++i) {
        number /= 10;
    }

    // Extract the last digit.
    return static_cast<int>(number % 10);
}

int main()
{
    long long number = 12345;

    std::cout << getDigitFromRight(number, 1) << '\n'; // 5
    std::cout << getDigitFromRight(number, 3) << '\n'; // 3
    std::cout << getDigitFromRight(number, 5) << '\n'; // 1

    return 0;
}



/*
run:

5
3
1

*/

 



answered 1 day ago by avibootz
...