$result = reduce($number);
function reduce($number) {
$new_number = 0;
if($number < 10) {
return $number;
}
$q = floor($number / 10 );
$r = $number % 10;
$new_number = $q + $r;
if($new_number <= 9) {
return $new_number;
}
else {
reduce($new_number);
}
}
I want to sum the numbers by its digits
For example, if i pass 10, it should return 1+0 = 1
This works if i pass 10
But not working when i pass 100.
You are missing the word return
near the end. It should look like this:
return reduce($new_number);
This should work for you:
Just split your number into an array with str_split()
and then use array_sum()
to add all digits together.
echo array_sum(str_split($number));
EDIT:
If you don't want the checksum, but go down to a single digit, you also don't have to write that much code. Just call the function over and over again until the array_sum()
is equal or less than 9.
function reduceToOneSingleDigit($result) {
$result = str_split($result);
while(array_sum($result) > 9)
return reduceToOneSingleDigit(array_sum($result));
return array_sum($result);
}
echo reduceToOneSingleDigit(99);
Just too much code, take a look at next one
print sum(125); // 8
// 5 12
// 2 1
// 1 + ~>0
function findSum($num)
{
if($num == 0)
return 0;
return $num%10 + findSum(floor($num/10));
}
so, even 100000 or 000001 will be 1, works just as U want, but it will have troubles if the paramater will be 0001000