【问题标题】:Get max number from given digit [PHP] [duplicate]从给定数字获取最大数字[PHP] [重复]
【发布时间】:2018-09-28 04:25:22
【问题描述】:

我正在尝试获取给定数字的最大可用数。

例如:

$inputDigit1 = 4;
$inputDigit2 = 9;
$inputDigit3 = 1;

输出应该是:

$outputDigit1 = 9999;
$outputDigit2 = 999999999;
$outputDigit3 = 9;

现在这是我的代码:

$output = '';
for ($i=0; $i < $inputDigit; $i++) { 
    $output.='9';
}
$output = (int) $output;

但我不知道在不使用循环的情况下解决这种情况的正确或更简单的方法。

【问题讨论】:

  • 为什么不创建一个数组而不是为每个值使用单个字符串? $inputDigit[1] = 4; $inputDigit2] = 9; $inputDigit[3] = 1;
  • 亲爱的@Bernhard。我只是用这个来解释我的情况。哈哈
  • 亲爱的@mickmackusa 感谢您的参考。我不知道之前是否有一个函数可以产生像 str_replace 这样的重复字符串。
  • 现在你知道了。从现在开始,您将知道在提问之前应该广泛搜索 StackOverflow。通常,您的问题的答案已经存在于这里的数百万页中。

标签: php numbers max digit


【解决方案1】:
<?php
$string='9';
$repeat=9;
echo str_repeat($string,$repeat);

//output 999999999

您可以设置输入字符串应重复的次数。

【讨论】:

    【解决方案2】:

    没有循环,使用str_repeat()

    <?php
    $inputDigit1 = 4;
    echo str_repeat($inputDigit1, $inputDigit1); // 4444
    

    虽然像 999999999 这样的数字会导致内存问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多