Thursday, 30 May 2013

How to reverse number using php

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

Steps to reverse a number:
1. Take modulas(%) of number by 10.
2. Now divide number by 10.
3. Repeat these steps until condition matches.

That's it you got the number reversed.

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

123456789 // actual number

987654321 // reversed number

No comments:

Post a Comment