/**
* Returns the N-th digit of a number counting from the right.
*
* Examples:
* getDigitFromRight(12345, 1) === 5
* getDigitFromRight(12345, 2) === 4
* getDigitFromRight(12745, 3) === 7
*
* @param {number} number - The input integer.
* @param {number} position - The digit position (1-based, from the right).
* @returns {number} The digit at the specified position.
* @throws {RangeError} If position is less than 1.
*/
function getDigitFromRight(number, position) {
if (!Number.isInteger(position) || position < 1) {
throw new RangeError("Position must be a positive integer.");
}
// Work with positive numbers only.
const absoluteNumber = Math.abs(number);
// Shift the desired digit to the ones place.
const shiftedNumber =
Math.floor(absoluteNumber / (10 ** (position - 1)));
// Extract the last digit.
return shiftedNumber % 10;
}
// Example usage
console.log(getDigitFromRight(12345, 1));
console.log(getDigitFromRight(12745, 3));
console.log(getDigitFromRight(12345, 5));
/*
run:
5
7
1
*/