珀尔 | Math::BigInt->digit() 方法
Perl 中的Math::BigInt
模块提供了表示具有任意精度和重载算术运算运算符的整数的对象。
Math::BigInt
模块的digit()
方法用于获取给定数字从右数的第 n位。要从左侧获取数字,我们需要将n指定为负数。
Syntax: Math::BigInt->digit($n)
Parameter:
$n: An integer value denoting the digit to be extracted.
Returns: an integer value which represents the nth digit of the given number counting from the right side.
示例 1:使用Math::BigInt->digit()
方法
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
$num = 7821593604;
# Create a BigInt object
$x = Math::BigInt->new($num);
# Initialize n
$n = 4;
# Get the nth digit
# counting from right side
$nth_digit = $x->digit($n);
print "${n}th digit in $num is $nth_digit.\n";
# Assign new value to n
$n = 6;
# Get the nth digit
# counting from right side
$nth_digit = $x->digit($n);
print "${n}th digit in $num is $nth_digit.\n";
输出:
4th digit in 7821593604 is 9.
6th digit in 7821593604 is 1.
示例 2:使用Math::BigInt->digit()
方法获取左起第 n 个数字
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
$num = 7821593604;
# Create a BigInt object
$x = Math::BigInt->new($num);
# To get nth digit form
# left side of the number
# we need to specify n
# as a negative number
# If n is negative then
# then method will return
# nth digit from left side
# but counting will start from 1.
# Initialize n
$n = 4;
# Get the nth digit
# from left side
$nth_digit = $x->digit(-$n);
print "${n}th digit from left in $num is $nth_digit.\n";
# Assign new value to n
$n = 6;
# Get the nth digit
# counting from left side
$nth_digit = $x->digit(-$n);
print "${n}th digit from left in $num is $nth_digit.\n";
输出:
4th digit from left in 7821593604 is 1.
6th digit from left in 7821593604 is 9.
示例 3:使用Math::BigInt->digit()
方法计算数字的位数之和
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
$num = 7821593604;
# Create a BigInt object
$x = Math::BigInt->new($num);
# Get the length of the number
$length = $x->length();
# Variable to store sum
$sum = 0;
# for loop to calculate
# sum of digits in given number
for($i = 0; $i < $length; $i++)
{
# Get the ith digit from the
# right side of the number
$sum = $sum + $x->digit($i);
}
# Print sum
print "Sum of digits in $num is $sum.";
输出:
Sum of digits in 7821593604 is 45.