Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to write reverse a number with recursive function in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

int rev_num(int n);

int main(void)
{
    printf("123 : %d\n", 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\n", 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\n", rev_num(1221));
            
    return 0;
}
int rev_num(int n) 
{
    return n < 10 ? n : (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
}


/*
run:
 
123 : 321
1234 : 4321
1221 : 1221

*/

 



answered Dec 11, 2015 by avibootz
edited Dec 12, 2015 by avibootz
...