Can the for loop be eliminated from this piece of PHP code?

后端 未结 10 1102
夕颜
夕颜 2020-12-11 04:59

I have a range of whole numbers that might or might not have some numbers missing. Is it possible to find the smallest missing number without using a loop structure? If ther

10条回答
  •  庸人自扰
    2020-12-11 05:47

    $range = array(0,1,2,3,4,6,7);
    
    $max=max($range);
    
    $expected_total=($max*($max+1))/2; // sum if no number was missing.
    
    $actual_total=array_sum($range);  // sum of the input array.
    
    if($expected_total==$actual_total){
       echo $max+1;      // no difference so no missing number, then echo 1+ missing number.
    }else{
       echo $expected_total-$actual_total; // the difference will be the missing number.
    }
    

提交回复
热议问题