View Full Version : Sum of Digits
11-23-2007, 11: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?
11-23-2007, 11:56 PM
- 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
11-24-2007, 02: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];
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.