标签:
设定在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; }
标签:
原文地址:http://www.cnblogs.com/520xiuge/p/5119629.html