The Weekly Challenge 258

Count Even Digits Number & Sum of Values

Official Challenge • Solutions on GitHub

Task 1: Count Even Digits Number

You are given an array of positive integers, @ints. Write a script to find out how many integers have an even number of digits.

Examples

Example 1: Input: @ints = (10, 1, 111, 24, 1000) Output: 3 # 10, 24, and 1000 have an even number of digits. Example 2: Input: @ints = (111, 1, 11111) Output: 0 Example 3: Input: @ints = (2, 8, 1024, 256) Output: 1

Logic

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.

Perl Solution (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;
}

Python Solution (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)

Task 2: Sum of Values

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.

Examples

Example 1: Input: @ints = (2, 5, 9, 11, 3), $k = 1 Output: 17 # Indices 1 (1), 2 (10), and 4 (100) have one 1-bit: 5 + 9 + 3 = 17. Example 2: Input: @ints = (2, 5, 9, 11, 3), $k = 2 Output: 11 # Index 3 (11) has two 1-bits: 11. Example 3: Input: @ints = (2, 5, 9, 11, 3), $k = 0 Output: 2 # Index 0 (0) has zero 1-bits: 2.

Logic

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.

Perl Solution (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;
}

Python Solution (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)