Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - reverse a number

I am coding in C on linux, and I need to reverse a number. (EG: 12345 would turn into 54321), I was going to just convert it into a string using itoa and then reverse that, as it's probably a lot easier with string manipulation, however it turns out itoa is non standard and isn't included in gcc. Is there a way of doing a binary rotation style thing on decimal numbers and if not what approach should I take?

like image 323
w4etwetewtwet Avatar asked May 08 '13 17:05

w4etwetewtwet


3 Answers

int n;
scanf("%d",&n);
int rev=0,rem;
while(n>0)
{
    rem=n%10; //take out the remainder .. so it becomes 5 for 12345
    rev=rev*10+rem; //multiply the current number by 10 and add this remainder.
    n=n/10; //divide the number. So it becomes 1234.
}
printf("%d",rev);
like image 53
Wayne Rooney Avatar answered Oct 13 '22 05:10

Wayne Rooney


#include<stdio.h>
main()
{
                 int rev=0,n;
                 scanf("%d",&n);
                 while(n)
                 {
                         rev=10*rev+n%10;
                         n/=10;
                 }
                 printf("result=%d",rev);
}
like image 39
lokesh5790 Avatar answered Oct 13 '22 04:10

lokesh5790


Do it without strings.

fkt()
   {
    int i = 12345;

    int n = 0;
    int x;
    char nr[10];
    char *p = &nr[0];

    while(i != 0)
    {
        x = i % 10;
        i = i/10;
        n = n * 10 + x;
        *p = x+'0';
        p++;
    }

    *p = 0;

    printf("%d   %s\n", n, nr);
    return 0;
}
like image 24
Devolus Avatar answered Oct 13 '22 04:10

Devolus