题解 | #[NOIP1999]回文数#
[NOIP1999]回文数
https://www.nowcoder.com/practice/a432eb24b3534c27bdd1377869886ebb
#include <stdio.h> #include<string.h> void SUM10(char* str1, char* str2, int len, int N)//N<=10 { int start = 0; int end = len - 1; int a = 0; int jw = 0; while (end >= 0) { str1[end] = str1[end] + jw; a = ((str1[end] - '0') + (str2[end] - '0')) % N; jw = ((str1[end] - '0') + (str2[end] - '0')) / N; str1[end] = a + '0'; end--; } if (jw > 0) { int i = 0; for (i = len; i > 0; i--) { str1[i] = str1[i - 1]; } str1[0] = jw + '0'; } } void SUM16(char* str1, char* str2, int len,int N) //N>10 { int start = 0; int end = len - 1; int a = 0; int i = 0; int j = 0; int jw = 0; while (end >= 0) { if (str1[end] + jw > '9'&&str1[end]<'A') { str1[end] = 'A'; } else { str1[end] += jw; } if (str1[end] >= 'A') { i = str1[end] - 'A' + 10; } else { i = str1[end] - '0'; } if (str2[end] >= 'A') { j = str2[end] - 'A' + 10; } else { j = str2[end] - '0'; } a = (i + j) % N; jw = (i + j) / N; if (a >= 10) { str1[end] = a - 10 + 'A'; } else { str1[end] = a + '0'; } end--; } if (jw > 0)//99位数字进1位 整体向后挪 { int i = 0; for (i = len; i > 0; i--) { str1[i] = str1[i - 1]; } str1[0] = '1'; } } void fz_16(char* str1, char* str2, int len) //翻转字符数组 { int i = 0; while (i < len) { str2[len - 1 - i] = str1[i]; i++; } } int is_hw(char* str, int len) //判断是否回文 1是 0否 { int start = 0; int end = len - 1; while (start < end) { if (str[start] != str[end]) { return 0; } else { start++; end--; } } return 1; } int main() { int N = 0; char M1[100] = { 0 }; char M2[100] = { 0 }; int STEP = 0; scanf("%d", &N); getchar(); scanf("%s", M1); int len = (int)strlen(M1); while (is_hw(M1, len) != 1) { if (STEP == 30) { printf("Impossible!\n"); return 0; } fz_16(M1, M2, len); if (N>10) { SUM16(M1, M2, len,N); } else { SUM10(M1, M2, len, N); } len = (int)strlen(M1); STEP++; } printf("STEP=%d\n", STEP); return 0; }