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,987 questions

51,931 answers

573 users

How to reverse the last N digits of an Integer in C

1 Answer

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

unsigned reverse_N_digits(unsigned last_N_digits, unsigned digits) {
    unsigned reverse = 0;
    while (digits--) {
        reverse = reverse * 10 + last_N_digits % 10;
        last_N_digits /= 10;
    }
    return reverse;
}

unsigned reverse_last_digits(unsigned x, unsigned digits) {
    unsigned pow10 = (unsigned)ceil(pow(10, digits));
    unsigned last_N_digits = x % pow10;
    unsigned without_last_N_digits = x - last_N_digits;

    return without_last_N_digits + reverse_N_digits(last_N_digits, digits);
}


int main(void) {
    printf("847421 : %u\n", reverse_last_digits(847421, 3));
    printf("981 : %u\n", reverse_last_digits(981, 2));
    printf("530006 : %u\n", reverse_last_digits(530006, 4));
    printf("31 : %u\n", reverse_last_digits(31, 2));
    printf("7 : %u\n", reverse_last_digits(7, 3));

    return 0;
}




/*
run:

847421 : 847124
981 : 918
530006 : 536000
31 : 13
7 : 700

*/


 



answered Oct 15, 2021 by avibootz

Related questions

1 answer 128 views
1 answer 111 views
1 answer 162 views
162 views asked Aug 10, 2021 by avibootz
1 answer 150 views
1 answer 134 views
...