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?
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);
#include<stdio.h>
main()
{
int rev=0,n;
scanf("%d",&n);
while(n)
{
rev=10*rev+n%10;
n/=10;
}
printf("result=%d",rev);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With