Caesar Cipher – HackerRank Solution

In this post, we will solve Caesar Cipher HackerRank Solution. This problem (Caesar Cipher) is a part of HackerRank Problem Solving series.

Julius Caesar protected his confidential information by encrypting it using a cipher.Â Caesar’s cipherÂ shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Example

s = There’s-a-starman-waiting-in-the-sky
k = 3

The alphabet is rotated byÂ 3, matching the mapping above. The encrypted string isÂ
Wkhuh’v-d-vwdupqd-zdlwlqj-lq-wkh-vnb.

Note: The cipher only encrypts letters; symbols, such as `-`, remain unencrypted.

Function Description

Complete the caesarCipher function in the editor below.

caesarCipher has the following parameter(s):

• string s: cleartext
• int k: the alphabet rotation factor

Returns

• string:Â the encrypted string

Input Format

The first line contains the integer,Â n, the length of the unencrypted string.
The second line contains the unencrypted string,Â s.
The third line containsÂ k, the number of letters to rotate the alphabet by.

Constraints

• 1 <= n <= 100
• 0 <= k <= 100
• sÂ is a valid ASCII string without any spaces.

Sample Input

``````11
middle-Outz
2``````

Sample Output

``okffng-Qwvb``

Explanation

``````Original alphabet:      abcdefghijklmnopqrstuvwxyz
Alphabet rotated +2:    cdefghijklmnopqrstuvwxyzab

m -> o
i -> k
d -> f
d -> f
l -> n
e -> g
-    -
O -> Q
u -> w
t -> v
z -> b``````

Solution – Caesar Cipher – HackerRank Solution

C++

```#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main(){
int n; cin >> n;
string s; cin >> s;
int k; cin >> k;

for (int i = 0; i <= n; i++) {
if (s[i] >= 'a' && s[i] <= 'z') { // if phrase is lowercase char
s[i] = ((s[i] - 'a' + k) % 26) + 'a'; // add key to it and wrap it in range
// this guarantees wrap-around, explicitly ensure phrase[i] is a char
} else if (s[i] >= 'A' && s[i] <= 'Z') { // same as if, but uppercase
s[i] = ((s[i] - 'A' + k) % 26) + 'A';
}
}
cout << s << endl;
return 0;
}
```

Python

```import sys
import string
symbols_low = string.ascii_lowercase
symbols_up = string.ascii_uppercase

def caesarCipher(s, k):
res = []
for c in s:
if c.isupper():
res.append(symbols_up[(symbols_up.index(c)+k)%len(symbols_up)])
elif c.islower():
res.append(symbols_low[(symbols_low.index(c)+k)%len(symbols_low)])
else:
res.append(c)

return "".join(map(str, res))

if __name__ == "__main__":
n = int(input().strip())
s = input().strip()
k = int(input().strip())
result = caesarCipher(s, k)
print(result)
```

Java

```import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length = scan.nextInt();
String str = scan.next();
int k = scan.nextInt();
scan.close();

StringBuilder sb = new StringBuilder();
for(int i = 0; i < str.length();i++)
{
char ch = str.charAt(i);
sb.append(encrypt(ch,k));
}
System.out.print(sb);
}

private static char encrypt(char x, int k)
{
if(!Character.isLetter(x))
return x;
char base = Character.isLowerCase(x)?'a':'A';
return (char) ((x-base+k)%26+base);
}
}
```

Note: This problem (Caesar Cipher) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.