PAT Basic 1048 数字加密 (20 分)

本题要求实现一种数字加密方法。首先固定一个加密用正整数 A,对任一正整数 B,将其每 1 位数字与 A 的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对 13 取余——这里用 J 代表 10、Q 代表 11、K 代表 12;对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。

输入格式:

输入在一行中依次给出 A 和 B,均为不超过 100 位的正整数,其间以空格分隔。

输出格式:

在一行中输出加密后的结果。

输入样例:

1234567 368782971

输出样例:

3695Q8118
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB

 

#include<iostream>
#include<stack>
using namespace std;
int main() {
    string s,s2;
    cin>>s>>s2;
    stack<int> sta1,sta2;
    stack<char> res;
    int tmp1,tmp2,tmpRes;
    for(int i=0;i<s.length();i++){
        sta1.push(s[i]-'0');
    }
    for(int i=0;i<s2.length();i++){
        sta2.push(s2[i]-'0');
    }
    bool isOdd=true;
    while(!sta1.empty()||!sta2.empty()){
        //取数值
        if(!sta1.empty()) {
            tmp1=sta1.top();
            sta1.pop();
        }else{
            tmp1=0;
        }
        if(!sta2.empty()) {
            tmp2=sta2.top();
            sta2.pop();
        }else{
            tmp2=0;
        }
        //奇偶处理数据
        if(isOdd){
            tmpRes=(tmp1+tmp2)%13;
            switch(tmpRes){
                case 10:res.push('J');break;
                case 11:res.push('Q');break;
                case 12:res.push('K');break;
                default:res.push(tmpRes+'0');break;
            }
        }else{
            tmpRes=tmp2-tmp1;
            if(tmpRes<0)tmpRes+=10;
            res.push(tmpRes+'0');
        }
        isOdd=!isOdd;
    }
    //output
    while(!res.empty()){
        cout<<res.top();
        res.pop();
    }
    system("pause");
    return 0;
}

 

 

posted @ 2019-08-05 04:09  SteveYu  阅读(170)  评论(0编辑  收藏  举报