Count Even Digits Number & Sum of Values
You are given an array of positive integers, @ints. Write a script to find out how many integers have an even number of digits.
For each integer in the input sequence, take its absolute value, convert it to its decimal string representation, and check whether its length is divisible by 2 (length % 2 == 0). Count how many elements satisfy this condition. Time complexity is O(n · d) where d is the maximum number of digits per integer.
ch-1.pl)#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
use Test::More;
signature_for count_even_digits => (
method => 0,
positional => [ ArrayRef [Int] ],
);
sub count_even_digits ($ints) {
my $even_digits_count = 0;
for my $num (@$ints) {
if ( length( abs($num) ) % 2 == 0 ) {
$even_digits_count++;
}
}
return $even_digits_count;
}
ch-1.py)def count_even_digits(ints: list[int] | tuple[int, ...]) -> int:
"""Count integers in the sequence that have an even number of digits."""
return sum(1 for num in ints if len(str(abs(num))) % 2 == 0)
You are given an array of integers, @ints, and an integer $k. Write a script to find the sum of values whose index binary representation has exactly $k number of 1-bit set.
Iterate over all 0-based indices i of the input array. Convert each index i to binary and count the number of 1 bits (popcount). Whenever the bit count equals $k, add $ints[$i] to the running total.
ch-2.pl)#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
use Test::More;
signature_for sum_of_values_with_k_ones => (
method => 0,
positional => [ ArrayRef [Int], Int ],
);
sub sum_of_values_with_k_ones ( $ints, $k ) {
my $sum = 0;
for my $index ( 0 .. $#$ints ) {
my $ones = () = sprintf( '%b', $index ) =~ /1/g;
$sum += $ints->[$index] if $ones == $k;
}
return $sum;
}
ch-2.py)def sum_of_values(ints: list[int], k: int) -> int:
"""Calculate the sum of values whose indices have exactly k 1-bits."""
return sum(value for i, value in enumerate(ints) if bin(i).count("1") == k)