How to get the Nth digit of a number from the right with BigInt support in JavaScript

1 Answer

0 votes
/**
 * Returns the N-th digit from the right for a BigInt.
 *
 * @param {bigint} number - The input integer.
 * @param {number} position - The digit position (1-based).
 * @returns {number} The extracted digit.
 */
function getDigitFromRightBigInt(number, position) {
    if (!Number.isInteger(position) || position < 1) {
        throw new RangeError("Position must be a positive integer.");
    }
 
    const divisor = 10n ** BigInt(position - 1);
 
    return Number((BigInt(number >= 0n ? number : -number) / divisor) % 10n);
}
 
// Example usage
console.log(getDigitFromRightBigInt(18092n, 3)); 
console.log(getDigitFromRightBigInt(180927345162343n, 1)); 
console.log(getDigitFromRightBigInt(180927345162341n, 7)); 
console.log(getDigitFromRightBigInt(123180927345162341n, 11)); 

 

/*
run:
 
0
3
5
2
 
*/

 



answered Oct 13 by avibootz

Related questions

...