DEV Community

Discussion on: Daily Challenge #54 - What century is it?

Collapse
 
choroba profile image
E. Choroba

This would've been even more interesting using the strict usage of "century" ;-)

#!/usr/bin/perl
use warnings;
use strict;

sub century {
    my ($year) = @_;
    my $century = 1 + int($year / 100);
    my $suffix;
    $suffix = 'th' if grep $century == $_, 11 .. 13;
    $suffix ||= {
        1 => 'st',
        2 => 'nd',
        3 => 'rd',
    }->{ substr $century, -1 } || 'th';
    $century . $suffix
}

use Test::More tests => 6;
is century(33),    '1st';
is century(2259), '23rd';
is century(1124), '12th';
is century(2000), '21st';
is century(3199), '32nd';
is century(2423), '25th';

First handle the exceptions (i.e. 11 - 13), then just use the last digit to decide.