設定在30次循環內判定str是否是回文字符串,不是則str與str的反置相加,將結果先賦給str1,
然後再賦回str
#include <stdio.h> #include <string.h> #include <stdlib.h> #define M 30 char str[M],str1[M]; int len; int Ispalindrome()//判斷回文數 { int i; for(i=0;i<len/2;i++) if(str[i] != str[len-i-1]) return 0; return 1; } int main() { int n,i,j,t; int t1,flag; char temp[2] = {'\0'}; scanf("%d%s",&n,&str); len = strlen(str); j = 0; flag = 0;if(n == 16) { for(t=0;t<30;t++)//30步以內得到回文數 { if(!Ispalindrome()) { for(i=0;i<len;i++) { t1 = 0; if(str[i]>='0' && str[i] <='9') t1 += (str[i] - '0'); else t1 += (str[i] - 'A' + 10); if(str[len-i-1]>='0' && str[len-i-1] <='9') t1 += (str[len-i-1] - '0'); else t1 += (str[len-i-1] - 'A' + 10); t1 += flag; if(t1 >= n)//要進位 { if(t1-n<= 9) itoa(t1-n,temp,10);//整型轉化為字符型 else temp[0] = 'A' + (t1-n-10); flag = 1; str1[j++] = temp[0]; } else{ if(t1<= 9) itoa(t1,temp,10);//整型轉化為字符型 else temp[0] = 'A' + (t1-10); flag = 0; str1[j++] = temp[0]; } } if(flag) { str1[j] = '1'; str1[j+1] = '\0'; flag = 0;//置0 } else str1[j] = '\0'; strcpy(str,str1);//將str1賦值給str len = strlen(str) ; j = 0; } else{ printf("STEP=%d\n",t); break; } } if(t == 30) printf("Impossible!\n"); } else{ for(t=0;t<30;t++)//30步以內得到回文數 { if(!Ispalindrome()) { for(i=0;i<len;i++) { t1 = (str[i]-'0') + (str[len-i-1] - '0') + flag;//要加flag if(t1 >= n)//要進位 { itoa(t1-n,temp,10);//整型轉化為字符型 flag = 1; str1[j++] = temp[0]; } else{ itoa(t1,temp,10);//整型轉化為字符型 flag = 0; str1[j++] = temp[0]; } } if(flag) { str1[j] = '1'; str1[j+1] = '\0'; flag = 0;//置0 } else str1[j] = '\0'; strcpy(str,str1);//將str1賦值給str j = 0; len = strlen(str) ; } else{ printf("STEP=%d\n",t); break; } } if(t == 30) printf("Impossible!\n"); } return 0; }