c程序反转数字

我正在寻找C程序来反转如下数字:

如果我输入:

123456

那么结果将是:

654321

请帮我。

使用% 10获取最后一位数字。 输出它。 将数字除以10得到除最后一位数之外的所有数字。 使用% 10来获取最后一位数字。 依此类推,直到数字变为0。

这是解决这个复杂问题的简单方法:

 #include  int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } } 

输出换行符的新版本:

 #include  #include  static void newline(void) { printf("\n"); } int main() { int ch; ch = getchar(); if (ch != '\n') { main(); printf("%c", ch); } else { atexit(newline); } } 

如果您的教授对您的表现进行评分,请在另一个问题中尝试ggf31416解决此问题的方法 :

 int FastReverse(int num) { int res = 0; int q = (int)((214748365L * num) >> 31); int rm = num - 10 * q; num = q; if (rm == 0) return -1; res = res * 10 + rm; while (num > 0) { q = (int)((214748365L * num) >> 31); rm = num - 10 * q; num = q; res = res * 10 + rm; } return res; } 

优化®

绝对时,必须要做到这一点纳秒。

这是另一种可能性。 它是非递归的,也许代码少一些。 代码注释中有一个例子来解释逻辑。

 /* Example: input = 12345 The following table shows the value of input and x at the end of iteration i (not in code) of while-loop. ---------------------- i | input | x ---------------------- 0 12345 0 1 1234 5 2 123 54 3 12 543 4 1 5432 5 0 54321 ---------------------- */ uint32_t reverseIntegerDigits( uint32_t input ) { uint32_t x = 0; while( input ) { x = 10 * x + ( input % 10 ); input = input / 10; } return x; } 

使用scanf("%s", A)读取char数组A的数字,或者更好地使用fgets读取数字,并通过输出从strlen(A) - 10开始的每个字符来反转char数组。

strrev函数反转字符串。 如果性能不是问题,那么例如你可以做itoa,然后是strrev,然后是atoi。 但即使没有strrev,任务也很简单。

看起来像一个非常古老的线程。 但我在这里提到了这些解决方案,并且在测试了本网站提供的不同程序后,不得不自己制作解决方案。 我意识到如果数字以零结尾,将数字视为int将不会产生必要的数字反转。 所以我决定将数字视为一个字符串然后反转数字。 这样,我从字符串的角度得到完全相反的数字,而不是在数字开头丢弃零的数学。

 #include  #include  main() { char num[20]; int x=0,slen; printf("Enter the number you want to reverse :"); scanf("%s",num); slen=strlen(num); char *pointertoarray = &num[slen]; for (x=slen;x>=0; x--){ printf("%c",*pointertoarray); pointertoarray--; } printf("\n"); } 
  1. 计算数字中的位数并存储在count变量中
  2. 提取变量中的个别数字
  3. 使用电源function。

     while(count>=1) { var = num % 10; sum = sum + var * pow(10, count - 1); num =num / 10; count--; }