5.3.1 6174问题
主要涉及了字符串的翻转
c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> using namespace std; int get_next(int x) { char num[5]; sprintf(num, "%d", x); int len = strlen(num); // buble sort for(int i = 0; i < len; i++) { for(int j = i+1; j < len; j++) { if(num[i] > num[j]) swap(num[i], num[j]); } } int b; sscanf(num, "%d", &b); for(int i = 0; i < len/2 ;i ++) { char t = num[i]; num[i] = num[len-1-i]; num[len-1-i] = t; } sscanf(num, "%d", &x); return x - b; } int main(int argc, const char *argv[]) { int num[2000], count; scanf("%d", &num[0]); count = 1; while(1) { bool find = false; int next = get_next(num[count - 1]); for(int i = 0; i < count; i++) if(next == num[i]) { find = 1; break; } if(find) { for(int i = 0; i < count; i++) printf("%d->", num[i]); printf("%d\n", next); break; } num[count++] = next; } return 0; }
5.3.2 字母重排
主要涉及到qsort的使用
c
#include <stdio.h> #include <string.h> #include <stdlib.h> const int maxl = 10; const int maxn = 200; int cmp_char(const void * _a, const void * _b) { char * a = (char*) _a; char * b = (char*) _b; return *a - *b; } int cmp_string(const void *_a, const void *_b) { char * a = (char*) _a; char * b = (char*) _b; return strcmp(a, b); } char word[maxn][maxl]; char sorted[maxn][maxl]; int main() { freopen("input", "r", stdin); int n = 0; while(1) { scanf("%s", word[n]); if(word[n][0] == '*') break; n++; } // 数组名,数组大小,单位大小,比较函数 qsort(word, n, sizeof(word[0]), cmp_string); for(int i = 0; i < n; i++) { strcpy(sorted[i], word[i]); qsort(sorted[i], strlen(sorted[i]), sizeof(char), cmp_char); } char t[10]; while(~scanf("%s", t)) { qsort(t, strlen(t), sizeof(char), cmp_char); int found = 0; for(int i = 0; i < n; i++) { if(strcmp(t, sorted[i]) == 0) { found = 1; printf("%s ", word[i]); } } if(!found) printf(":("); printf("\n"); } return 0; }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。