...

View Full Version : Sum of Digits



MindTheGap
11-23-2007, 10:44 PM
Is there anyway to find the sum of digits of an expression in PHP?

For example, if I needed to find the sum of the digits of 2^10, how would I do that?

srule_
11-23-2007, 10:56 PM
HINT:
- You Got to use "%" operator.
- You Got to use A Loop

Ill start the code for you, See if you can finish it:



$remain = 0
$num = Whatever you want

while ($remain != $num)
{
$remain = $num % 10; // Extract rightmost digit
$sum += $remain; // Sum digits

.... Finish Me

Inigoesdr
11-24-2007, 01:36 AM
Or you could cast it to a string:

$numbers = 1234567890;
$temp = (string) $numbers;
$total = 0;
for($i = 0; $i < strlen($numbers); $i++)
$total += $temp[$i];



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum