A
A
Arthur 816242016-03-09 11:54:51
PHP
Arthur 81624, 2016-03-09 11:54:51

How to create a program for adding digits of an n-digit number?

In general, this is what I blinded:

<?php

  $num = 1679;

  if ($num > 9)
  {
    $numOne = $num % 10;                                      // 9
    $modOne = ($num - $numOne) / 10;                          // 167

    if ($modOne > 9)
    {
      $numTwo = $modOne % 10;                                 // 7
      $modTwo = ($modOne - $numTwo % 10) / 10;                // 16

      if ($modTwo > 9)
      {
        $numThree = $modTwo % 10;                             // 6
        $modThree = ($modTwo - $numThree % 10) / 10;          // 1

        $numPen = $numOne + $numTwo + $numThree + $modThree;  // 23

        if ($numPen > 9)
        {
          $numFour = $numPen % 10;                            // 3
          $modFour = ($numPen - $numFour % 10) / 10;          // 2

          $numFin = $numFour + $modFour;                      // 5
        }
      }
    }
  }

  echo $numFin;

?>

Probably, it is better to solve this problem by a cycle? How? Can it be made universal?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
look2009, 2016-03-09
@Arthur81624

$arr1 = str_split($num);
Rotate the array and add.
Only check is_numeric do. If from outside the incoming parameter.
Maybe there will be points if is_numeric does a check, then a regular expression will help.
It is better to write 1 function and twist it until there is a single-digit number.

R
Ravshan Abdulaev, 2016-03-09
@ravshanium

If you need to add numbers, then it's probably easier to do this:

<?php

  $num = 1679;

  $numFin = '';

 preg_match_all('/(\w)/', $num, $m);
 
for ($i = 0; $i < count($m[0]); $i++){
  
  $d = ($i == count($m[0])-1)?'':'+';
   echo $m[0][$i].$d;
  $numFin +=$m[0][$i];

}
echo '=';
echo $numFin;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question