Largest 5 digit number in a series

Viewed 1986

I've been trying to solve the following issue for days now, I just cannot wrap my head around it:

In the following 10 digit number:

1234567890

67890 is the greatest sequence of 5 consecutive digits.

Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.

So far, what I've been trying to do is to split the string into an array ($arr = str_split($s);) and use a for loop to iterate through the entire thing.

The next steps (iterate through five values, save it as a variable, check the variable, and if its not the highest, discard it) are an absolute mystery to me.

I've tried looking through Stackoverflow for helpful advice, and haven't been able to find anything on the subject. If I'm wrong, my apologies.

3 Answers

I tried it by using substr

$fullNumber = 1234567898765;
$biggestNumber = 0;

for ($i = 0; $i <= strlen($fullNumber) - 5; $i++) {
    $nextNumber = substr($fullNumber, $i, 5);
    if ($nextNumber > $biggestNumber) {
        $biggestNumber = $nextNumber;
    }
}

echo $biggestNumber;

Considering below as you string of digits:

$str = '123456789012345678901234567890';

Take one variable to store greatest number, than through loop, you will get sub string of 5 digits and store it in $greatest_number variable.

$greatest_number =  0;

for($i=0;$i < strlen($str) - 5;$i++){
  $substr = (int)substr($str,$i,5);

  if($greatest_number < $substr){
    $greatest_number = $substr;
  }

}

Using Recursion. In php simple 4 lines code will work.

<?php


    sol("2505656");
    function sol($d){
        if(strlen($d) <=5) return $d;
        echo ''.max(substr($d,5)),sol(substr($d,1));
    }
    ?>

EDIT 3:
Add error_reporting(1); in start of the document. Because these errors are warning. So just ignore that.

Related