Get the sum of digits in PHP

后端 未结 13 2681
攒了一身酷
攒了一身酷 2020-11-29 10:45

How do I find the sum of all the digits in a number in PHP?

相关标签:
13条回答
  • 2020-11-29 11:41

    Assume you want to find the sum of the digits of a number say 2395 the simplest solution would be to first split the digits and find out the sum then concatenate all the numbers into one single number.

    <?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";
         ?>
    
    0 讨论(0)
  • 2020-11-29 11:41
    // 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;
    
    0 讨论(0)
  • 2020-11-29 11:43

    Artefactos method is obviously unbeatable, but here an version how one could do it "manually":

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

    This is actually faster than Artefactos method (at least for 1234567890), because it saves two function calls.

    0 讨论(0)
  • 2020-11-29 11:44
    array_sum(str_split($number));
    

    This assumes the number is positive (or, more accurately, that the conversion of $number into a string generates only digits).

    0 讨论(0)
  • 2020-11-29 11:46

    Another way, not so fast, not single line simple

    <?php
    
        $n = 123;
        $nstr = $n . "";
    
        $sum = 0;
        for ($i = 0; $i < strlen($nstr); ++$i)
        {
            $sum += $nstr[$i];
        }
        echo $sum;
    
    ?>
    

    It also assumes the number is positive.

    0 讨论(0)
  • 2020-11-29 11:46
    function addDigits($num) {
    
        if ($num % 9 == 0 && $num > 0) {
            return 9;
        } else {
              return $num % 9;
            }
        }
    

    only O(n)

    at LeetCode submit result: Runtime: 4 ms, faster than 92.86% of PHP online submissions for Add Digits. Memory Usage: 14.3 MB, less than 100.00% of PHP online submissions for Add Digits.

    0 讨论(0)
提交回复
热议问题