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,
you can use stack to do this,
struct node
{
char character;
struct node *next;
};
struct node *list_head,*neos;
main()
{
list_head=NULL;
char str[14];
int number,i;
scanf("%d",&number);
sprintf(str,"%d",number); //here i convert number to string
for(i=0;i<strlen(str);i++) //until the end of the string
{
add_to_stack(str[i]); //i take every character and put it in the stack
}
print_the_number();
}
attention here,in stack the item which is added last, it taken out first, that why it works..
void add_to_stack(char charac)
{
neos=(struct node*)malloc(sizeof(struct node));
neos->character=charac;
neos->next=list_head;
list_head=neos;
}
void print_the_number()
{
struct node *ptr;
ptr=list_head;
while(ptr!=NULL)
{
printf("%c",ptr->character);
ptr=ptr->next;
}
}
iota()
is not a standard C function, but snprintf()
serves the purpose just as well.
/* assume decimal conversion */
const char * my_itoa (int input, char *buffer, size_t buffersz) {
if (snprintf(buffer, sz, "%d", input) < sz) return buffer;
return 0;
}
Since the input cannot be negative, you can use an unsigned type:
unsigned long long irev (unsigned input) {
unsigned long long output = 0;
while (input) {
output = 10 * output + input % 10;
input /= 10;
}
return output;
}
Reversing the input may result in a value that no longer fits the input type, so the return result attempts to use a wider type. This may still fail if unsigned
and unsigned long long
have the same width. For such cases, it is probably easiest to use a string to represent the reversed value. Or, if the only goal is to print the number, you can just use a loop to print the digits in reverse order.
void print_irev (unsigned input) {
if (input) {
do {
putchar('0' + input % 10);
input /= 10;
} while (input);
} else {
putchar('0');
}
putchar('\n');
}
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 really want to use strings, you can use sprintf to do what itoa does.
int k = 12345;
char str[40];
sprintf(str,"%d",k);
Then reverse the string and convert it back to int using atoi or sscanf.