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

2 Answers

0 votes
/**
 * Returns the N-th digit of a number counting from the right.
 *
 * Examples:
 * getDigitFromRight(12345, 1) => 5
 * getDigitFromRight(12345, 2) => 4
 * getDigitFromRight(12845, 3) => 8
 *
 * @param int $number   The input number.
 * @param int $position The digit position (1-based, from the right).
 *
 * @return int The digit at the specified position.
 *
 * @throws InvalidArgumentException If the position is less than 1.
 */
function getDigitFromRight(int $number, int $position): int
{
    if ($position < 1) {
        throw new InvalidArgumentException(
            'Position must be greater than 0.'
        );
    }

    // Work with positive numbers only.
    $number = abs($number);

    // Shift the desired digit to the ones place.
    $number = intdiv($number, 10 ** ($position - 1));

    // Extract the last digit.
    return $number % 10;
}

// Example usage
echo getDigitFromRight(12345, 1) . PHP_EOL; 
echo getDigitFromRight(12845, 3) . PHP_EOL; 
echo getDigitFromRight(12345, 5) . PHP_EOL; 



/*
run:

5
8
1

*/

 



answered 1 day ago by avibootz
0 votes
/**
 * Returns the N-th digit from the right (1-based).
 */
function getDigitFromRight(int $number, int $position): int
{
    if ($position < 1) {
        throw new InvalidArgumentException(
            'Position must be greater than 0.'
        );
    }

    return intdiv(abs($number), 10 ** ($position - 1)) % 10;
}

// Example usage
echo getDigitFromRight(12345, 1) . PHP_EOL; 
echo getDigitFromRight(12845, 3) . PHP_EOL; 
echo getDigitFromRight(12345, 5) . PHP_EOL; 


/*
run:

5
8
1

*/

 



answered 1 day ago by avibootz
...