/
ch-2.pl
53 lines (43 loc) · 1.23 KB
/
ch-2.pl
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
#!/usr/bin/perl
use strict;
use warnings;
sub is_additive {
my ($str) = @_;
my $n = length($str);
for my $i ( 1 .. $n / 2 ) {
# Ensure first number doesn't start with a '0'
next if ( $str =~ m/^0/ && $i > 1 );
for my $j ( 1 .. ( $n - $i ) / 2 ) {
# Ensure second number doesn't start with a '0'
next if ( $str =~ m/^.$j\d/ && $j > 1 );
if ( check_sequence( $str, $i, $j ) ) {
return 1;
}
}
}
return 0;
}
sub check_sequence {
my ( $str, $i, $j ) = @_;
my $n = length($str);
my $first = substr( $str, 0, $i );
my $second = substr( $str, $i, $j );
for ( my $k = $i + $j ; $k < $n ; ) {
my $next = $first + $second;
my $next_s = "$next";
my $len = length($next_s);
if ( $k + $len <= $n && $next_s eq substr( $str, $k, $len ) ) {
$first = $second;
$second = $next;
$k += $len;
}
else {
return 0;
}
}
return 1;
}
# Test cases
print is_additive('112358') ? "true\n" : "false\n";
print is_additive('12345') ? "true\n" : "false\n";
print is_additive('199100199') ? "true\n" : "false\n";