Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and work.

aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Linux Training
Teach Your Child To Read

BlueHost Web Hosting Black Friday

Bonsai Boy of New York Bonsai Trees and Accessories

DreamCloud The Comfortable Luxury Mattress Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

16,864 questions

22,528 answers

573 users

How to write reverse number function using recursion in PHP

2 Answers

0 votes
/*
number pow( number $base , number $exp )
float log10( float $arg )
*/

function rev_num($n) 
{
    return $n < 10 ? $n : ($n % 10) * pow(10, (int)log10($n)) + rev_num($n / 10);
}

printf("123 : %d<br />", rev_num(123));
/*
 * (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
 *    3     *     10 ^ 2 = 300       + rev_num(12)
 *    2     *     10 ^ 1 = 20        + rev_num(1)
 *    1     *     10 ^ 0 = 1         + rev_num(0)
 *   300 + 20 + 1 = 321; 
 */
     
printf("1234 : %d<br />", rev_num(1234));
/*
 * (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
 *    4     *     10 ^ 3 = 4000      + rev_num(123)
 *    3     *     10 ^ 2 = 300       + rev_num(12)
 *    2     *     10 ^ 1 = 20        + rev_num(1)
 *    1     *     10 ^ 0 = 1         + rev_num(0)
 *   4000 + 300 + 20 + 1 = 4321; 
 */
 
printf("1221 : %d<br />", rev_num(1221));


/*
run:

123 : 321
1234 : 4321
1221 : 1221

*/

 




answered Dec 15, 2015 by avibootz
0 votes
/*
number pow( number $base , number $exp )
float log10( float $arg )
*/

function rev_num($n) 
{
    return $n < 10 ? $n : ($n % 10) * pow(10, (int)log10($n)) + rev_num($n / 10);
}

echo "123 : " . intval(rev_num(123)) . "<br />";
/*
 * (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
 *    3     *     10 ^ 2 = 300       + rev_num(12)
 *    2     *     10 ^ 1 = 20        + rev_num(1)
 *    1     *     10 ^ 0 = 1         + rev_num(0)
 *   300 + 20 + 1 = 321; 
 */
     
echo "1234 : " . intval(rev_num(1234)) . "<br />";
/*
 * (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
 *    4     *     10 ^ 3 = 4000      + rev_num(123)
 *    3     *     10 ^ 2 = 300       + rev_num(12)
 *    2     *     10 ^ 1 = 20        + rev_num(1)
 *    1     *     10 ^ 0 = 1         + rev_num(0)
 *   4000 + 300 + 20 + 1 = 4321; 
 */
 
echo "1221 : " . intval(rev_num(1221)) . "<br />";


/*
run:

123 : 321
1234 : 4321
1221 : 1221

*/

 




answered Dec 15, 2015 by avibootz
...