![](/img/trans.png)
[英]Why is reverse of a number c program written with the concept of digits places instead like the below one which I posted?
[英]c program for the reverse the digits
我正在尋找C
程序來反轉數字,如下所示:
如果我輸入:
123456
那么結果將是:
654321
請幫我。
這是解決此復雜問題的簡單方法:
#include <stdio.h>
int main()
{
int ch;
ch = getchar();
if (ch != '\n') {
main();
printf("%c", ch);
}
}
#include <stdio.h> #include <stdlib.h> 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;
}
如果絕對如此,那么肯定必須在十億分之一秒內完成。
使用% 10
獲取最后一位數字。 輸出它。 將數字除以10可得到除最后一位以外的所有數字。 使用% 10
來獲取該數字的最后一位。 依此類推,直到數字變為0。
這是另一種可能性。 它是非遞歸的,也許更少的代碼。 在代碼注釋中有一個示例來說明邏輯。
/*
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)
或最好使用fgets
讀取char數組A
的數字,並通過輸出從strlen(A) - 1
到0
每個字符來輸出反轉的char數組。
看起來很舊。 但是我在這里提到了解決方案,並且在測試了本網站上作為解決方案可用的其他程序之后,不得不自己編寫解決方案。 我意識到,如果數字以零結尾,則將數字視為int不會產生必要的數字反轉。 因此,我決定將數字視為字符串,然后反轉數字。 這樣,從字符串的角度來看,我得到的是數字的完全相反,而不是從數字的開頭丟棄零的數學式。
#include <stdio.h>
#include <string.h>
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");
}
strrev函數反轉字符串。 如果性能不是問題,那么您可以執行itoa,strrev和atoi。 但是即使沒有strrev,任務也非常簡單。
使用電源功能。
while(count>=1) { var = num % 10; sum = sum + var * pow(10, count - 1); num =num / 10; count--; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.