Thursday, 30 May 2013

How to reverse number and add using php

Many time interviewer asked me to write a program to reverse a number and add. So i am sharing this program with you.

Steps to reverse a number and add:

  • Take modulas(%) of number by 10. 
  • Add this number until condition matches. 
  • Now divide number by 10. 
  • Repeat these steps until condition matches.

That's it you got the number reversed and added.

<?php
             echo 'How to reverse number and add using php ';
             echo '<br>';
             echo $numberToReverse = 123456789;
             echo '<br>';
             if($numberToReverse > 0){
                    $sum = 0;
                    while($numberToReverse){
                           echo $numberToReverse%10;
                           $sum += $numberToReverse%10;
                           $numberToReverse = (int)($numberToReverse/10);
                     }
                     echo '<br>';
                     echo 'Sum of number : '.$sum;
              }else{
                     echo 'number should be grater then zero.';
              }
?>

Output is:
How to reverse number and add using php

123456789 // actual number

987654321 // reversed number

Sum of number : 45

No comments:

Post a Comment