HackerRank Caesar Cipher Problem Solution
In this post, we will solve HackerRank Caesar Cipher Problem Solution.
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.
Original alphabet: Alphabet rotated +3:
abcdefghijklmnopqrstuvwxyz defghijklmnopqrstuvwxyzabc
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-vwdupdq-zdlwlqj-1q-wkh-vnb.
Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.
unction 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.
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
Caesar Cipher C Solution
#include <stdio.h>
void encode (char in[], char en[], int n, int k)
{
if (k > 26)
k = k % 26;
int i;
for (i = 0; i < n; ++i)
{
if ((in[i] >= 65 && in[i] <= 90-k) || (in[i] >= 97 && in[i] <= 122-k))
en[i] = in[i] + k;
else if ((in[i] >= 90-k && in[i] <= 90) || (in[i] >= 122-k && in[i] <= 122))
en[i] = in[i] - 26 + k;
else
en[i] = in[i];
}
en[i] = '\0';
}
int main()
{
int n;
scanf ("%d", &n);
char in[n];
scanf ("%s", in);
int k;
scanf ("%d", &k);
char en[n+1];
encode (in, en, n, k);
//en[n] = '\0';
printf ("%s\t", en);
return 0;
}
Caesar Cipher C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int rot;
char a;
string s;
cin >> rot;
cin >> s;
cin >> rot;
for(auto &c: s){
if(isalpha(c)){
a = isupper(c)?'A':'a';
c= a + (c - a + rot)%26;
}
}
cout << s << endl;
return 0;
}
Caesar Cipher C Sharp Solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
class Solution {
static void Main(String[] args) {
var tamanhoDaString = Convert.ToInt16(Console.ReadLine());
var textoNormal = Console.ReadLine();
var chave = Convert.ToInt32(Console.ReadLine());
var textoCriptografado = "";
for (int i = 0; i < tamanhoDaString; i++)
{
if (char.IsUpper(textoNormal[i]))
{
var letraASerCodificada = char.ToLower(textoNormal[i]);
if (_alfabeto.Contains(letraASerCodificada))
{
var letraCodificada = RetornaLetraCodificada(letraASerCodificada, chave);
letraCodificada = char.ToUpper(letraCodificada);
textoCriptografado += letraCodificada;
}
}
else if (char.IsLower(textoNormal[i]))
{
if (_alfabeto.Contains(textoNormal[i]))
{
var letraCodificada = RetornaLetraCodificada(textoNormal[i], chave);
textoCriptografado += letraCodificada;
}
}
else
{
textoCriptografado += textoNormal[i];
}
}
Console.WriteLine(textoCriptografado);
}
public static char RetornaLetraCodificada(char letraASerCodificada, int chave)
{
var posicaoDaNovaLetra = (_alfabeto.IndexOf(letraASerCodificada))+chave;
while (posicaoDaNovaLetra >= 26)
{
posicaoDaNovaLetra -= 26;
}
var novaLetra = _alfabeto[posicaoDaNovaLetra];
return novaLetra;
}
private static string _alfabeto = "abcdefghijklmnopqrstuvwxyz";
}
Caesar Cipher Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'caesarCipher' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. STRING s
* 2. INTEGER k
*/
public static String caesarCipher(String s, int k) {
// Write your code here
final int _k = k % 26;
return s.chars()
.boxed()
.map(c -> {
if (c >= 97 && c <= 122)
if ((c + _k) > 122)
return 97 + ((c + _k) % 122) - 1;
else return c + _k;
else if (c >= 65 && c <= 90)
if ((c + _k) > 90)
return 65 + ((c + _k) % 90) - 1;
else return c + _k;
else return c;
})
.mapToInt(Integer::intValue)
.mapToObj((a -> (char) a))
.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
String s = bufferedReader.readLine();
int k = Integer.parseInt(bufferedReader.readLine().trim());
String result = Result.caesarCipher(s, k);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Caesar Cipher JavaScript Solution
function processData(input) {
var lines = input.split("\n");
var len = lines.shift();
var knockedOffFirstLine = lines.join("\n");
var str = knockedOffFirstLine.substring(0, len);
var rot = parseInt(knockedOffFirstLine.substring(len, knockedOffFirstLine.length));
var newStr = "";
for (var i=0; i< str.length; i++) {
var char = str.charAt(i);
var newChar = shift(char, rot);
newStr += newChar;
}
return newStr;
}
function shift(char, rot) {
const A = 65;
const Z = 90;
const a = 97;
const z = 122;
var code = char.charCodeAt(0);
var isUpper = code >= A && code <= Z;
var isLower = code >= a && code <= z;
if (!isUpper && !isLower) return char;
var baseOffset = isUpper ? A : a;
var encCode = code - baseOffset;
encCode += rot;
encCode = encCode % ((Z-A)+1);
encCode += baseOffset;
var encChar = String.fromCharCode(encCode);
return encChar;
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
process.stdout.write(processData(_input));
});
Caesar Cipher Python Solution
n = input()
string = input()
k = int(input())%26 # shift
encrypted = []
for character in string:
if character.isalpha():
if character.isupper():
startIndex = ord("A")
else:
startIndex = ord("a")
difference = ord(character) - startIndex
encrypted.append(chr((difference + k)%26 + startIndex))
else:
encrypted.append(character)
print("".join(encrypted))
Other Solutions