この問題にはさまざまな解決策が存在することは理解していますが、解決策を確認した後、コードがどこで失敗しているかわかりません。参考までに私のコードは次のとおりです。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strrev(char *str)
{
if (!str || ! *str)
return str;
int i = strlen(str) - 1, j = 0;
char ch;
while (i > j)
{
ch = str[i];
str[i] = str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main(){
long int a,b, ab, maxA, maxB, pal;
long int maxPal = 0;
char string[6];
char revString[6];
for(a=999; a>100; a--){
for(b=999; b>100; b--){
ab = a*b;
sprintf(string,"%ld",ab);
strcpy(revString, strrev(string));
strrev(string);
if((revString[0] != '0') && (strcmp(string, revString)== 0)){
printf("Palindrome %ld found!\n", ab);
pal = ab;
if(pal > maxPal){
maxPal = pal;
maxA = a;
maxB = b;
}
}
}
}
printf("Maximim palindrome is %ld from the product of a = %ld and b = %ld \n", maxPal, maxA, maxB);
return 1;
}
私は、100から999までの数字のすべてのペアを調べ、積を文字列に変換してから、文字列が逆方向に同じであるかどうかを確認することにより、力ずくの方法でこれを試みています。ただし、これを行うと、最大の回文として6桁の数字ではなく5桁の数字しか見つかりません。私の論理はかなり単純に思えますが、間違った結論に達しています。正しい答えではなく、自分の論理の何が間違っているのかを理解したいと思います。
見つかった回文の数を数えるようにコードを変更しました。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strrev(char *str)
{
if (!str || ! *str)
return str;
int i = strlen(str) - 1, j = 0;
char ch;
while (i > j)
{
ch = str[i];
str[i] = str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main(){
long int a,b, ab, maxA, maxB, pal;
long int maxPal = 0;
char string[6];
char revString[6];
int n6dp = 0;
int n5dp = 0;
for(a=999; a>100; a--){
for(b=999; b>100; b--){
ab = a*b;
sprintf(string,"%ld",ab);
strcpy(revString, strrev(string));
strrev(string);
if((revString[0] != '0') && (strcmp(string, revString)== 0)){
if (strlen(string) == 6)
{
n6dp++;
}
if (strlen(string) == 5)
{
n5dp++;
}
pal = ab;
if(pal > maxPal){
maxPal = pal;
maxA = a;
maxB = b;
}
}
}
}
printf("number of 5 digits palindroms found = %d\n", n5dp);
printf("number of 6 digits palindroms found = %d\n", n6dp);
printf("Max. palindrome is %ld from the product of a = %ld and b = %ld \n", maxPal, maxA, maxB);
return 0;
}
これが私が得るものです:
$ ./pal
number of 5 digits palindroms found = 1493
number of 6 digits palindroms found = 977
Max. palindrome is 906609 from the product of a = 993 and b = 913
あなたのコードは6桁の回文を見つけました。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加