Caesar's Cipher

Caesar's Cipher is a very famous encryption technique used in cryptography. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, D would be replaced by G, E would become H, X would become A, and so on.

Encryption of a letter X by a shift K can be described mathematically as EK(X)=(X+K) % 26.

Given a plaintext and its corresponding ciphertext, output the minimum non-negative value of shift that was used to encrypt the plaintext or else output -1 if it is not possible to obtain the given ciphertext from the given plaintext using Caesar's Cipher technique.

Example:

Input:  A = "ABC", B = "DEF"
Output: 3

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int caesarCipher(string Astring B)
{
    unordered_map<charintump;
    for (int i = 0i < 26i++)
        ump['A' + i] = i;
    if (A == B)
        return 0;
    else
    {
        int k = 0;
        for (int j = 0j <= 26j++)
        {
            if ((ump[A[0]] + j) % 26 == ump[B[0]])
            {
                k = j;
                break;
            }
        }

        int flag = 0;
        for (int i = 1i < B.size(); i++)
        {
            if ((ump[A[i]] + k) % 26 != ump[B[i]])
            {
                flag = 1;
                break;
            }
        }
        if (flag)
            return -1;
        else
            return k;
    }
}
int main()
{

    string A = "ABC"B = "DEF";

    cout << caesarCipher(AB<< "\n";

    return 0;
}


No comments:

Post a Comment