1. 程式人生 > >PAT乙 1048. 數字加密(20)

PAT乙 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; }