【问题标题】:Find missing numbers in array [closed]在数组中查找缺失的数字[关闭]
【发布时间】:2013-09-13 14:38:05
【问题描述】:

我有一个包含 99 个数字的 php 数组。

数组包含 1 到 100 的数字,但缺少一位。

如何知道丢失的号码?

【问题讨论】:

  • 全部加起来,然后从 5050 中减去总数?
  • 你为什么不试着自己做作业?
  • 这是给你的作业。请发表您的答案。
  • 我得到了答案。谢谢大家。

标签: php arrays numbers digit


【解决方案1】:

既然你说你自己找到了答案,这里有一个可能的解决方案

$assignmentArray = array(1,2,3,4,5,6,7,8,10);

// find the missing fie... err.. missing value is actually more correct.
$missingNumber = array_sum(range(1, 10)) - array_sum($assignmentArray);
echo 'The missing number is: ' . $missingNumber;

【讨论】:

  • 此代码随机显示单个数字。我想不随机显示单个缺失的数字。
  • @ChinmaySahu:您应该更改 assignmentArray 以反映您应该搜索的数组。既然你有一个数组,你显然不需要生成一个。
  • 当我使用 $assignmentArray=array(1,2,3,4,5,6,7,8,10); 然后缺少的数字显示 9 但不可能在数组中分配大量数字。
  • @ChinmaySahu:查看更新的答案
  • 是的,这是正确的,但问题在于大量数组。是否可以在数组中定义1到100000?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2012-10-11
  • 2011-11-11
  • 2017-11-07
  • 2014-04-19
相关资源
最近更新 更多