1048. 数字加密(20)
题目地址:1048. 数字加密(20)
题目描述:
本题要求实现一种数字加密方法。首先固定一个加密用正整数A,对任一正整数B,将其每1位数字与A的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对13取余——这里用J代表10、Q代表11、K代表12;对偶数位,用B的数字减去A的数字,若结果为负数,则再加10。这里令个位为第1位。
输入格式:
输入在一行中依次给出A和B,均为不超过100位的正整数,其间以空格分隔。输出格式:
在一行中输出加密后的结果。
Tips:
这里要考虑到A比B长的情况。而且此时B用0填充,另外还要考虑到A比B长的那部分,如果是那一位A为0,则不用+10
程序:
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string A, B;
cin >> A >> B;
char Map[13] = {'0','1','2','3','4','5','6','7','8','9','J','Q','K'};
int lenA = A.length();
int lenB = B.length();
int flag = 0; // 用于来确定是奇数位还是偶数位
char output[100];
int outputIdx = 99;
int i;
for (i = lenA - 1; i >= 0; i--)
{
if (lenB == 0)
{
if (flag == 0)
{
flag = 1;
// printf("1 %c\n", A[i]);
output[outputIdx--] = A[i];
}
else
{
flag = 0;
if ((0 - (A[i]-'0') < 0))
{
output[outputIdx--] = (10 - (A[i] - '0') + '0');
}
else
{
output[outputIdx--] = A[i];
}
}
}
else
{
if (flag == 0)
{
flag = 1;
output[outputIdx--] = Map[((A[i]-'0') + (B[--lenB]-'0')) % 13];
}
else
{
int anw = (B[--lenB]-'0')-(A[i]-'0');
output[outputIdx--] = (char)(anw >= 0 ? anw : anw + 10) + '0';
flag = 0;
}
}
}
if (lenB > 0)
{
for (int j = 0; j < lenB; j++)
printf("%c", B[j]);
}
for (int i = 100 - lenA; i < 100; i++)
printf("%c", output[i]);
printf("\n");
return 0;
}