Caesar Cipher Algorithm in C++


You are given a lowercase alphabet string s, and an offset integer k. Replace every letter in s with a letter k positions further along the alphabet. Note: If the letter overflows past a or z, it gets wrapped around the other side.

Example 1
Input
s = “abc”
k = 2
Output
“cde”
Explanation
“abc” gets moved 2 positions to the right.

Example 2
Input
s = “aaa”
k = -1
Output
“zzz”
Example 3
Input
s = “zzz”
k = 1
Output
“aaa”

Explanation
The “z” gets wrapped to “a”

Simple Caesar Cipher (Rot) Algorithm in C++

Given the input is all lowercase characters, we can rotate and replace in place the original characters using O(N) time and O(1) space. The K has to be modulous by 26 and add 26 in case it is negative.

1
2
3
4
5
6
7
string caesarCipherAlgorithm(string s, int k) {
    k %= 26;
    for (auto &n: s) {
        n = 'a' + (n - 'a' + k + 26) % 26;
    }
    return s;
}
string caesarCipherAlgorithm(string s, int k) {
    k %= 26;
    for (auto &n: s) {
        n = 'a' + (n - 'a' + k + 26) % 26;
    }
    return s;
}

You may want to look at other caesar ciphers for example: ROT47 Algorithm

String Cipher Algorithms

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
346 words
Last Post: Teaching Kids Programming - 3 Different Approaches to Solve Two-Sum Problem
Next Post: Teaching Kids Programming - Two Algorithms to Compute Inverse Factorials

The Permanent URL is: Caesar Cipher Algorithm in C++

Leave a Reply