生成具有给定长度的相同数字

问题描述 投票:0回答:3

我有这个数学作业,我应该在代码中。我已经尝试了所有想法,但我找不到解决方案。所有这些都应该在不使用php函数的情况下完成,只需要数学运算你可以使用while,for和...

所以我有数字例如9现在我应该创建长度9的数量,这将是999999999

例如,如果我有数字3,那么结果应该是333

有任何想法吗?

$gen = -1;
while($highest > 0) {
    $gen = $highest + ($highest * 10);
    $highest = $highest - 1;
}

echo $gen;
php math integer repeat
3个回答
4
投票

这是一个不构建字符串的方法;它使用纯数学。 (将有许多方法来完成这项任务)

$x=9;
$result=0;
for($i=$x; $i; --$i){         // this looping expression can be structured however you wish potato-potatoe
   $result+=$x*(10**($i-1));  // x times (10 to the power of (i-1))
}
echo $result;
// 999999999

*注意:如果你想查找它,**就像pow()一样。


后期编辑:这是一个聪明的,无环的方法(安静地自豪)。我只是打电话给range()foreach()进行演示;它不是我方法的组成部分。

但是:ぁzxswい

https://3v4l.org/GIjfG

输出:

foreach(range(0,9) as $n){
    // echo "$n -> ",(integer)(1/9*$n*(10**$n)-($n/10)),"\n";
    // echo "$n -> ",(1/9*$n*(10**$n)-(1/9*$n)),"\n";
    // echo "$n -> ",(int)(1/9*10**$n)*$n,"\n";
    // echo "$n -> ",(int)(10**$n/9)*$n,"\n";
    echo "$n -> ",(10**$n-1)/9*$n,"\n";
}

0 -> 0 1 -> 1 2 -> 22 3 -> 333 4 -> 4444 5 -> 55555 6 -> 666666 7 -> 7777777 8 -> 88888888 9 -> 999999999 是这种方法的英雄,因为它生成1/9(重复)。从这个浮点数,我使用.111111111“移动”恰好足够的10**$ns到小数点的左侧,然后将这个浮点数乘以1,然后浮点数必须转换为一个整数才能完成。

Per @axiac的评论,新的英雄是$n,它生成一系列所需长度的9(没有浮点数)。接下来将九分为九,以产生一系列成为完美乘数的系数。最后,将一系列1和输入数相乘,得到所需的输出。


3
投票

您需要完成两项操作:

  1. 给出一个数字10**$n-1,将数字$number附加到它;
  2. 重复操作#1一些次数($n次)。

操作#1很简单:

$n

操作#2更容易:

$number = $number * 10 + $n;

你还需要什么? 用于存储计算数字的变量的初始化:

for ($i = 0; $i < $n; $i ++)

把它们整理好,你得到:

$number = 0;

2
投票

如果接受// The input digit // It gives the length of the computed number // and also its digits $n = 8; // The number we compute $number = 0; // Put the digit $n at the end of $number, $n times for ($i = 0; $i < $n; $i ++) { $number = $number * 10 + $n; } // That's all

intval()

其他:

$result = '';
$input = 9;
for($i=0; $i < $input; $i++){
    $result .= $input;
}
$result = intval($result);

=> 9 + 90 + 900 + 9000 + 90000...

© www.soinside.com 2019 - 2024. All rights reserved.