获取PHP中的数字总和

时间:2010-07-12 21:44:07

标签: php string sum

如何在PHP中找到数字中所有数字的总和?

13 个答案:

答案 0 :(得分:99)

array_sum(str_split($number));

这假设数字是正数(或者更确切地说,$number到字符串的转换只生成数字)。

答案 1 :(得分:13)

Artefactos方法显然是无与伦比的,但这里有一个版本如何“手动”做到:

$number = 1234567890;
$sum = 0;
do {
    $sum += $number % 10;
}
while ($number = (int) $number / 10);

这实际上比Artefactos方法更快(至少对于1234567890),因为它节省了两个函数调用。

答案 2 :(得分:4)

另一种方式,不是那么快,不是单行简单

<?php

    $n = 123;
    $nstr = $n . "";

    $sum = 0;
    for ($i = 0; $i < strlen($nstr); ++$i)
    {
        $sum += $nstr[$i];
    }
    echo $sum;

?>

它还假设数字是正数。

答案 3 :(得分:1)

<?php 
// PHP program to calculate the sum of digits 
function sum($num) { 
    $sum = 0; 
    for ($i = 0; $i < strlen($num); $i++){ 
        $sum += $num[$i]; 
    } 
    return $sum; 
} 

// Driver Code 
$num = "925"; 
echo sum($num); 
?> 

结果将为9 + 2 + 5 = 16

答案 4 :(得分:0)

请尝试以下代码:

<?php

$num = 525;
$sum = 0;

while ($num > 0)
{
    $sum= $sum + ($num % 10);
    $num= $num / 10;
}
echo "Summation=" . $sum;

?>

答案 5 :(得分:0)

如果对正则表达式感兴趣:

CREATE TABLE myLogs (             
   USER_ID  varchar(20) NOT NULL,     
   LOG_DATE  date NOT NULL,           
   LOGGER  varchar(50) NOT NULL,      
   LEVEL  varchar(10) NOT NULL,       
   MESSAGE  varchar(1000) NOT NULL   
);

答案 6 :(得分:0)

假设您想要找到一个数字的总和,比如2395,最简单的解决方案是首先拆分数字并找出总和,然后将所有数字连接成一个数字。

<?php
    $number=2;
    $number1=3;
    $number2=9;
    $number3=5;
    $combine=$number.$number1.$number2.$number3;
    $sum=$number+$number1+$number2+$number3;
    echo "The sum of $combine is $sum";
     ?>

答案 7 :(得分:0)

    <?php
echo"----Sum of digit using php----";
echo"<br/ >";
$num=98765;
$sum=0;
$rem=0;
for($i=0;$i<=$num;$i++)
{
$rem=$num%10;
$sum=$sum+$rem;
$num=$num/10;
}
echo "The sum of digit 98765 is ".$sum;
?>
-----------------Output-------------
----Sum of digit using php----
The sum of digit 98765 is 35

答案 8 :(得分:0)

// math before code 

// base of digit sums is 9 

// the product of all numbers multiplied by 9 equals 9 as digit sum

$nr = 58821.5712; // any number

// Initiallization 

$d = array();

$d = explode(".",$nr); // cut decimal digits

$fl = strlen($d[1]); // count decimal digits

$pow = pow(10 ,$fl); // power up for integer

$nr = $nr * $pow; // make float become integer

// The Code

$ds = $nr % 9; // modulo of 9 

if($ds == 0) $ds=9; // cancel out zeros

echo $ds;

答案 9 :(得分:0)

function addDigits($num) {

    if ($num % 9 == 0 && $num > 0) {
        return 9;
    } else {
          return $num % 9;
        }
    }

只有O(n)

在LeetCode提交结果: 运行时间:4毫秒,快于Add Digits的PHP在线提交的92.86%。 内存使用量:14.3 MB,不到PHP在线提交的“添加数字”的100.00%。

答案 10 :(得分:-1)

<html>
<head>
<title>detail</title>
</head>
<body>
<?php
$n = 123;
$sum=0; $n1=0;

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

  $n1=$n%10;

   $sum += $n1;
   $n=$n/10;
  }
 echo $sum;

 ?>
 </body>
</html>

答案 11 :(得分:-1)

这是代码..请试试这个

   <?php 
    $d=0;
   $num=12345;

   $temp=$num;

   $sum=0;

   while($temp>1)

     {
      $temp=$temp/10;

        $d++;
         }

     echo "Digits Are : $d </br>";

      for (;$num>1;)

             {
              $d=$num%10;

             $num=$num/10;

             $sum=$sum+$d;

             }

           echo "Sum of Digits is : $sum";

   ?>

答案 12 :(得分:-1)

获取数字总和的一种方法,但这是最慢的路线。

return StreamBuilder<QuerySnapshot>(
    stream: mapsService.helpCalls,
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (!snapshot.hasData) return Container();

      return Container(
        height: 200,
        color: Colors.green,
        child: ListView(
          scrollDirection: Axis.horizontal,
          children:
              snapshot.data.documents.map((DocumentSnapshot document) {
            return IgnorePointer(
                              child: Container(
                                color: Colors.white,
                child: Column(children: <Widget>[
                  Text(document.data["latitude"].toString()),
                  Text("Faszinierend!"),
                ],),
              ),
            );
          }).toList(),
        ),
      );
    });