题目链接:http://codeforces.com/problemset/problem/616/A
题目意思:顾名思义,就是比较两个长度不超过 1e6 的字符串的大小
模拟即可。提供两个版本,数组版本 & 指针版本。
(1)数组版本(短的字符串从高位处补0,直到跟长的字符串长度相同)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 using namespace std; 6 7 const int maxn = 1e6 + 5; 8 char a[maxn], b[maxn]; 9 int rev_a[maxn], rev_b[maxn]; 10 11 int cmp(int len) 12 { 13 int f = 0; // 0: a=b; 1: a>b; 2: a<b 14 // 比较的时候要从高位比起,存储的时候是从低位开始存的 15 for (int i = len-1; i >= 0 && !f; i--) { 16 if (rev_a[i] > rev_b[i]) { 17 f = 1; 18 } 19 else if (rev_a[i] < rev_b[i]) { 20 f = 2; 21 } 22 } 23 return f; 24 } 25 26 int main() 27 { 28 #ifndef ONLINE_JUDGE 29 freopen("in.txt", "r", stdin); 30 #endif // ONLINE_JUDGE 31 32 while (scanf("%s%s", a, b) != EOF) { 33 int la = strlen(a); 34 int lb = strlen(b); 35 36 for (int i = 0; i < la; i++) { 37 rev_a[la-i-1] = a[i]-‘0‘; 38 } 39 40 for (int i = 0; i < lb; i++) { 41 rev_b[lb-i-1] = b[i]-‘0‘; 42 } 43 44 int flag = 0; 45 // 保证比较的字符串长度相等, 0补上 46 if (la < lb) { // la < lb 47 for (int i = 0; i < lb-la; i++) { 48 rev_a[la+i] = 0; 49 } 50 flag = cmp(lb); 51 } 52 else { // la >= lb 53 for (int i = 0; i < la-lb; i++) { 54 rev_b[lb+i] = 0; 55 } 56 flag = cmp(la); 57 } 58 if (flag == 1) puts(">"); 59 else if (flag == 2) puts("<"); 60 else puts("="); 61 } 62 return 0; 63 }
(2)指针版本(过滤前缀0之后,再逐位比较大小)
1 /* 2 指针版本 3 */ 4 #include <iostream> 5 #include <cstdio> 6 #include <cstdlib> 7 #include <cstring> 8 using namespace std; 9 10 const int maxn = 1e6 + 5; 11 char a[maxn], b[maxn]; 12 13 int cmp(char *s1, char *s2) 14 { 15 // 过滤前缀 0 16 while (*s1 == ‘0‘) { 17 s1++; 18 } 19 while (*s2 == ‘0‘) { 20 s2++; 21 } 22 23 int l1 = strlen(s1); 24 int l2 = strlen(s2); 25 if (l1 > l2) { 26 return ‘>‘; 27 } 28 else if (l1 < l2) { 29 return ‘<‘; 30 } 31 // a,b长度相等(l1 = l2) 32 for (int i = 0; i < l1; i++) { 33 if (*s1 < *s2) { // 指针指向的值 34 return ‘<‘; 35 } 36 else if (*s1 > *s2) { 37 return ‘>‘; 38 } 39 s1++; // 指针右移一位 40 s2++; 41 } 42 return ‘=‘; 43 } 44 45 46 int main() 47 { 48 #ifndef ONLINE_JUDGE 49 freopen("in.txt", "r", stdin); 50 #endif // ONLINE_JUDGE 51 52 while (scanf("%s%s", a, b) != EOF) { 53 printf("%c\n", cmp(a, b)); 54 } 55 return 0; 56 }
时间: 2024-10-11 00:00:15