C - reverse a number

后端 未结 6 1187
时光取名叫无心
时光取名叫无心 2020-12-18 05:58

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,

6条回答
  •  执笔经年
    2020-12-18 06:30

    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

    }

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

提交回复
热议问题