C – 反转一个数字

我在Linux上用C编码,我需要反转一个数字。 (EG:12345将变成54321),我只是将它转换为使用itoa的字符串然后反转,因为它可能更容易使用字符串操作,但事实certificateitoa是非标准的并且不包括在内在gcc。 有没有办法在十进制数字上做二进制旋转样式的事情,如果不是我应该采取什么方法?

 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 main() { int rev=0,n; scanf("%d",&n); while(n) { rev=10*rev+n%10; n/=10; } printf("result=%d",rev); } 

没有字符串。

 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; } 

如果你真的想使用字符串,你可以使用sprintf来做itoa所做的事情。

 int k = 12345; char str[40]; sprintf(str,"%d",k); 

然后反转字符串并使用atoi或sscanf将其转换回int。

你可以使用堆栈来做到这一点,

 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 

}

注意这里,在堆栈中最后添加的项目,它首先取出,它为什么工作..

 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()不是标准的C函数,但snprintf()可以达到目的。

 /* 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; } 

由于输入不能为负数,因此可以使用无符号类型:

 unsigned long long irev (unsigned input) { unsigned long long output = 0; while (input) { output = 10 * output + input % 10; input /= 10; } return output; } 

反转输入可能会导致值不再适合输入类型,因此返回结果会尝试使用更宽的类型。 如果unsignedunsigned long long具有相同的宽度,则这可能仍然失败。 对于这种情况,使用字符串来表示反转值可能最容易。 或者,如果唯一的目标是打印数字,您可以使用循环以相反的顺序打印数字。

 void print_irev (unsigned input) { if (input) { do { putchar('0' + input % 10); input /= 10; } while (input); } else { putchar('0'); } putchar('\n'); }