Answer the question
In order to leave comments, you need to log in
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;
?>
Answer the question
In order to leave comments, you need to log in
$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.
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 questionAsk a Question
731 491 924 answers to any question