本题要求实现一种数字加密方法。首先固定一个加密用正整数 A,对任一正整数 B,将其每 1 位数字与 A 的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对 13 取余——这里用 J 代表 10、Q 代表 11、K 代表 12;对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。
输入格式:
输入在一行中依次给出 A 和 B,均为不超过 100 位的正整数,其间以空格分隔。
输出格式:
在一行中输出加密后的结果。
输入样例:
1234567 368782971
输出样例:
3695Q8118
#include<iostream>
#include<string.h>
#include<string>
#include<stack>
using namespace std;
int main()
{
string strA,strB;
cin>>strA>>strB;
stack <char>s;
int lenA = strA.size(), lenB = strB.size();
int digit = 1;
if(lenA > lenB)
{
strB.insert(0,lenA - lenB,'0');
}
if(lenA < lenB)
{
strA.insert(0,lenB - lenA,'0');
}
int i = strA.size(), j = strB.size();
while(i&&j)
{
if(digit % 2 == 1)//奇数位
{
int temp = (strA[--i] -'0' )+ (strB[--j] -'0');
temp = temp % 13;
if(temp < 10)
{
s.push(temp + '0');
}
else
{
switch (temp)
{
case 10 :
s.push('J');
break;
case 11 :
s.push('Q');
break;
case 12 :
s.push('K');
break;
}
}
}
if(digit % 2 == 0) //偶数位
{
int tempodd = (strB[--j] - '0' ) - (strA[--i] -'0');
if(tempodd >= 0)
{
s.push(tempodd + '0');
}
else
{
tempodd += 10;
s.push(tempodd + '0');
}
}
digit ++;
}
while(!s.empty())
{
cout<<s.top();
s.pop();
}
return 0;
}
这题看似简单,但是实则很多问题,首先如果一个长度不够,需要另一个字符串前面!!!注意前面补0!!!!
我开始是从前往后输出,但是, 由于奇数、偶数数位问题导致我自己混乱,所以就用了个栈stack,把数字怼进去,
最后在输出出来就好啦
版权声明:本文为Yolanda_Salvatore原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。