1048 数字加密(20 分)

1048 数字加密(20 分)

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

输入格式:

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

输出格式:

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

输入样例:

1234567 368782971

输出样例:

3695Q8118

思考

/*翻转字符串*/
void reverse(char s[]){
	int len =strlen(s);
	for(int i=0;i<len/2;i++){//注意条件
		int temp=s[i];
		s[i]=s[len-1-i];
		s[len-1-i]=temp;
	}
}

AC代码

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;

char A[101], B[101];

void  reverse(char s[])
{
    for(int i = 0, j = strlen(s) - 1; i < j; i ++, j --){
        swap(s[i], s[j]);
    }
} 

void solve()
{
    reverse(A);
    reverse(B);

    int lenA = strlen(A), lenB = strlen(B);
    if(lenA < lenB){
        int i;
        for(i = lenA; i < lenB; i ++)
            A[i] = '0';
        A[i] = 0;
    }
    else{
        int i;
        for(i = lenB; i < lenA; i ++)
            B[i] = '0';
        B[i] = 0;
    }

    int len = max(lenA, lenB);
    char C[101] = {0};
    char ch[] = "0123456789JQK";

    for(int i = 0; i < len; i ++){

        //对奇数位,对应位的数字相加后对13取余——这里用J代表10、Q代表11、K代表12
        if((i + 1) & 1){
            C[i] = ch[(A[i]- '0' + B[i] - '0') % 13];
        }

        //对偶数位,用B的数字减去A的数字,若结果为负数,则再加10
        else{
            C[i] = ch[(B[i] - A[i] + 10) % 10];
        }
    }

    reverse(C);
    cout << C << endl;
}

int main()
{
    cin >> A >> B;
    solve();
    return 0;
}

这代码思路和胡凡一致,不过是c++而非c语言

下面给出c语言的代码

#include <stdio.h>
#include <string.h>
#define maxn 110
char A[maxn],B[maxn],ans[maxn]={0};
void reverse(char s[]){
	int len =strlen(s);
	for(int i=0;i<len/2;i++){
		int temp=s[i];
		s[i]=s[len-1-i];
		s[len-1-i]=temp;
	}
}
int main(){
	scanf("%s %s",A,B);
	reverse(A);
	reverse(B);
	int lenA=strlen(A);
	int lenB=strlen(B);
	int len=lenA>lenB ? lenA:lenB;
	for(int i=0;i<len;i++){
		int numA=i< lenA?A[i]-'0':0;
		int numB=i< lenB?B[i]-'0':0;
		if(i%2==0){
			int temp = (numA+numB)%13;
			if(temp == 10)
				ans[i]='J';
			else if(temp==11)
				ans[i]='Q';
			else if(temp==12)
				ans[i]='K';
			else ans[i] = temp+'0';
		}else {
			int temp=numB-numA;
			if(temp<0)
				temp+=10;
			ans[i]=temp+'0';	
		}
	}
	reverse(ans);
	puts(ans);
	return 0;	
} 
posted @ 2018-08-10 07:57  lingr7  阅读(494)  评论(0编辑  收藏  举报