3 February 2015

Quiz 80: Remove leading zeros from an array of positive integers

Problem:

Given an array of positive integers, display an array after removing all the leading zeros from original array.

Input Format: 

array having elements separated by "space"

Output Format: 

array having elements separated by "space" after removing leading zeros

Constraints: 
Each element of array is < 1000000

Sample Input

007 70 01022 0000000001 00200 20000 0012300

Sample Output:

7 70 1022 1 200 20000 12300

Explanations:

Simple, removed all zeros before first non-zero character



Solution:

use strict;
use warnings;

chomp(my $line=<>);
my @arr=split(" ",$line);
@arr=map{$_%1000000}@arr;
print "@arr";

Tips:

Use mod of maximum value ie 1000000 in our case.

4 comments:

  1. echo '007 70 01022 0000000001 00200 20000 0012300' | perl -pe 's/\b0+//g'

    ReplyDelete
  2. what if I have 12 leading zeroes. will your code work properly? You are diving just by 10^6.

    Why don't you use Perl's most powerful weapon that is regex :)

    $str =~ s/^0+//g'; and then do split and print array :)

    ReplyDelete
  3. Hi
    your solution will not work for 00 or 0. Will give NULL. Expected should be 0.

    ReplyDelete
  4. Constraints are provided in problem solution. Each element of array is < 1000000. I can use divide by 1 to make it work for any length.

    ReplyDelete