PTA 乙级 1048 数字加密 (20分) C++

 

 最一开始想直接用整型,%10不断取余的处理方式,但是测试点4,5无法通过,原因在代码后面

 1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 int main() {
 8     long a = 0, b = 0;    //必须用long,否则测试点0无法通过
 9     int an = 0, bn = 0;
10     int odd = 0, even = 0;
11     char arr[] = { '0','1','2','3','4','5','6','7','8','9','J','Q','K' };
12     string s;
13     cin >> a >> b;
14     for (int i = 1; b % 10 != 0 || a % 10 != 0; ++i) {
15         an = a % 10;
16         bn = b % 10;
17         a /= 10;
18         b /= 10;
19         if (i % 2 != 0) {
20             odd = (an + bn) % 13;
21             s += arr[odd];
22         }
23         else {
24             even = bn - an;
25             if (even < 0) even += 10;
26             s += to_string(even);
27         }
28     }
29     reverse(s.begin(), s.end());
30     cout << s;
31     return 0;
32 }

 

 

 以测试点5为例:

数字B的位数小于数字A的位数,而且数字A前面有0.
例如: A=000456 B=789
正确输出:000Q32
错误输出::0:Q32

这一版的代码就会出现这样的毛病,测试点4同理,B前有0的话无法补全

所以只能用字符串处理了

 1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 int main() {
 8     string a, b;    
 9     /*奇位数,偶位数*/
10     int odd = 0, even = 0;
11     /*1~13位*/
12     char arr[] = "0123456789JQK";
13     string s;
14     cin >> a >> b;
15     reverse(a.begin(), a.end());        //进行反转,从正整数个位开始处理
16     reverse(b.begin(), b.end());
17     if (a.length() > b.length())        //比较长度,补0位
18         b.append(a.length() - b.length(), '0');
19     else
20         a.append(b.length() - a.length(), '0');
21     for (int i = 0; i <a.length(); ++i) {
22         if (i % 2 == 0) {                //i为偶数即为原数字的奇数位
23             odd = (a[i]-'0' + b[i] - '0') % 13;
24             s = arr[odd] + s;
25         }
26         else {
27             even = (b[i] - '0') - (a[i] - '0');
28             if (even < 0) even += 10;
29             s = to_string(even) + s;
30         }
31     }
32     cout << s;
33     return 0;
34 }

 

posted @ 2020-08-10 23:29  上帝的绵羊  阅读(421)  评论(0编辑  收藏  举报