aboutsummaryrefslogtreecommitdiff
path: root/challenge-140/mohammad-anwar/perl/ch-1.pl
blob: 9b18109dd7e8bbd7fd45bd936916fa317e8d238e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/perl

=head1

Week 140:

    https://theweeklychallenge.org/blog/perl-weekly-challenge-140

Task #1: Add Binary

    You are given two decimal-coded binary numbers, $a and $b.

    Write a script to simulate the addition of the given binary numbers.

=cut

package Binary;

use strict;
use warnings;

use overload '+' => 'add', '""' => 'stringify';

sub new {
    my ($class, $value) = @_;
    my $self = {
        binary  => $value,
        decimal => oct("0b" . $value),
    };

    bless $self, $class;

    return $self;
}

sub add {
    my ($self, $other) = @_;

    return Binary->new( sprintf("%b", $self->{decimal} + $other->{decimal}) );
}

sub stringify {
    my ($self) = @_;

    return $self->{binary};
}

package main;

use Test::More;

my $ex1 = Binary->new('11')  + Binary->new('1');
my $ex2 = Binary->new('101') + Binary->new('1');
my $ex3 = Binary->new('100') + Binary->new('11');

is("$ex1", '100', 'Example 1');
is("$ex2", '110', 'Example 2');
is("$ex3", '111', 'Example 3');

done_testing;