All about the way

numbers are written

Weekly challenge 258 — 26 February 2024

;

Task 1

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

Example 1Input: @ints = (10, 1, 111, 24, 1000) Output: 3 There are 3 integers having even digits i.e. 10, 24 and 1000.Example 2Input: @ints = (111, 1, 11111) Output: 0Example 3Input: @ints = (2, 8, 1024, 256) Output: 1

This is a pretty easy one-liner, thanks to Perl's willingness to treat integers as numeric values or strings of digits depending on context. The one line is:

$count += 1 - (length($_) % 2) for @_;

The `length`

call returns the numbers of digits in each of `@ints`

,
the`% 2`

returns the remainder on diving that by 2, which will be 0 or 1,
and the `1 - `

swaps those to 1 or 0, which is what we are asked to count.

As we are treating `@ints`

purely as a string of digits this works
even if any of the numbers strays into BigInt territory, but sadly Perl won't
(easily) print a number with more than 15 digits other than in
floating point format.

#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-02-26 use utf8; # Week 258 - task 1 - Count even digits number use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; count_even_digits_number (10, 1, 111, 24, 1000); count_even_digits_number (111, 1, 11111); count_even_digits_number (2, 8, 1024, 256); count_even_digits_number (1234567890123456789901234567890, 12345678901234567890, 123456789); sub count_even_digits_number { # count @ints with even length my $count = 0; $count += 1 - (length($_) % 2) for @_; say qq[\nInput: (] . join(', ', @_) . ')'; say qq[Output: $count]; }

Input: (10, 1, 111, 24, 1000) Output: 3 Input: (111, 1, 11111) Output: 0 Input: (2, 8, 1024, 256) Output: 1 Input: (1.23456789012346e+30, 12345678901234567890, 123456789) Output: 2

Any content of this website which has been created by Peter Campbell Smith is in the public domain