C - reverse a number

后端 未结 6 1191
时光取名叫无心
时光取名叫无心 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:37

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

提交回复
热议问题