Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: Sum of Digits

  1. #1
    New Coder
    Join Date
    Jul 2007
    Posts
    67
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Sum of Digits

    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?

  • #2
    Regular Coder
    Join Date
    Jul 2007
    Posts
    571
    Thanks
    25
    Thanked 28 Times in 28 Posts
    HINT:
    - You Got to use "%" operator.
    - You Got to use A Loop

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

    PHP Code:
    $remain 0
    $num 
    Whatever you want

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

     
    .... Finish Me 
    Last edited by srule_; 11-24-2007 at 12:02 AM.

  • #3
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    Or you could cast it to a string:
    PHP Code:
    $numbers 1234567890;
    $temp = (string) $numbers;
    $total 0;
    for(
    $i 0$i strlen($numbers); $i++)
        
    $total += $temp[$i]; 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •