UVA 444 Encoder and Decoder

本文介绍了一个使用ASCII码进行字符加密和解密的C++程序。该程序能够根据输入的字符类型,实现数字的解密和字母及其他符号的加密。通过倒序循环和字符数组操作,实现了对字符串的有效处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:按照规则。若是数字则解密,若是字母和其他符号则加密。

分析:略

考点:ASCII 码对 数字 的转换。字符数组(字符串)。倒序循环。整数(最大三位)分离单个数字。

注意:字符数组大小要大一点。题目说“a spy’s message is at most 80 characters long”是指 字母加密(读入字母的长度)。解密的长度至少应该为80*3+1。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char a[512]={0};int zimu;
    while(fgets(a,81,stdin))
    {
        a[strlen(a)-1]=0;
        if(isdigit(a[0]))
        {
            for(int i=strlen(a)-1;i>=0;i--)
            {
                if(a[i]==1)
                {
                    zimu=1*100+(a[i-1]-'0')*10+a[i-2]-'0';
                    i=i-2;
                    printf("%c",(char)zimu);
                }
                else
                {
                    zimu=(a[i]-'0')*10+a[i-1]-'0';
                    i=i-1;
                    printf("%c",(char)zimu);
                }
            }
            printf("\n");
        }
        else
        {
            for(int i=strlen(a)-1;i>=0;i--)
            {
                zimu=(int)a[i];
                if(zimu/100==0)
                {
                    printf("%d%d",zimu%10,zimu/10);
                }
                else
                    printf("%d%d%d",zimu%10,(zimu/10)%10,1);
            }
            printf("\n");
        }
    }
    return 0;
}

老师代码参考:

/*ad hoc. */
#include <string>
#include <iostream>
#include <cctype>
using namespace std;
void encode(string &code);
void decode(string &code);
int main() {
    string str;
    while(getline(cin,str)) {
        if(isdigit(str[0]))//第1个字符是数字,表示需要解密
            decode(str);
        else//第1个字符不是数字,表示需要加密
            encode(str);
    }
    return 0;
}
void decode(string &code){
    for(int i=code.size()-1; i>=0; ){//倒序处理每个数字字符 
        int asc=0;
        int count=2; //设后面将处理2个数字字符
        if(code[i]=='1'){//后面将处理3个数字字符 
            count=3;
        }
        while( count-- ){
            asc=asc*10+code[i]-'0';
            i--;
        }
        cout<<(char)asc;
    }
    cout<<endl;
}
void encode(string &code) {
    for(int i=code.size()-1; i>=0; i--) {//倒序处理每个字符 
        char asc=code[i];
        while(asc>0) {//从低位到高位输出 
            cout<<asc%10;
            asc/=10;
        }
    }
    cout<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值