PAT B1048 数字加密
输入样例:
1234567 368782971
输出样例:
3695Q8118
-
要把短的那个向长的那个用0补齐!!!
-
思路1:
将字符串逆序存到两个数组里,再从头遍历数组,用一个栈逆序输出 -
code1:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stack>
using namespace std;
char thirteen[15] = "0123456789JQK";
stack<char> st;
int main(){
string n1, n2;
cin >> n1 >> n2;
int a1[110] = {0}, a2[110] = {0};
for(int i = 1; i <= n1.size(); ++i){
//倒序存入数组
a1[i] = n1[n1.size()-i] - '0';
}
for(int i = 1; i <= n2.size(); ++i){
a2[i] = n2[n2.size()-i] - '0';
}
int len2 = n2.size();
if(n2.size() < n1.size()) len2 = n1.size();
for(int i = 1; i <= len2; ++i){
if(i % 2 == 1){
st.push(thirteen[(a2[i]+a1[i])%13]);
}else{
char c = (a2[i] + (10 - a1[i])) % 10 + '0';
st.push(c);
}
}
while(!st.empty()){
cout << st.top();
st.pop();
}
return 0;
}
-
思路2:
将2个字符串reverse,然后用两个while补齐,再用一个for循环从头遍历处理,结果保存在另一个字符串内 -
code2:
#include <iostream>
#include <string>
#include <algorithm>
#include <stdio.h>
using namespace std;
char thirteen[15] = "0123456789JQK";
int main(){
string n1, n2, ans;
cin >> n1 >> n2;
reverse(n1.begin(), n1.end());
reverse(n2.begin(), n2.end());
while(n1.size() < n2.size()){
n1 += '0';
}
while(n1.size() > n2.size()){
n2 += '0';
}
for(int i = 0; i < n1.size(); ++i){
int x1 = n1[i] - '0';
int x2 = n2[i] - '0';
if((i+1) % 2 == 1){
ans += thirteen[(x1+x2) % 13];
}else{
char c = (x2+10-x1)%10 + '0';
ans += c;
}
}
reverse(ans.begin(), ans.end());
cout << ans;
return 0;
}
-
思路3:
step1:先补齐
step2:直接正向遍历,len-i即为从后往前数的次序 -
code 3:
#include <bits/stdc++.h>
using namespace std;
char mark[15] = "0123456789JQK";
int main(){
string a, b;
cin >> a >> b;
while(a.size() < b.size()) a.insert(0, "0");
while(b.size() < a.size()) b.insert(0, "0");
for(int i = 0; i < a.size(); ++i){
int dig_a = a[i] - '0', dig_b = b[i] - '0';
if((a.size() - i) % 2){
printf("%c", mark[(dig_a + dig_b) % 13]);
}else{
printf("%d", (dig_b - dig_a + 10) % 10);
}
}
return 0;
}