HackerRank Caesar Cipher Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Caesar Cipher Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Caesar Cipher Solution
HackerRank Caesar Cipher Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Caesar Cipher Solution

Ezoicreport this adTask

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

HackerRank Caesar Cipher Solution

Caesar Cipher Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
		int i,j,k,g,n,m=0;scanf("%d",&n);
    char ch1[130]={'a'},ch2[130]={'A'},s[100];scanf("%s",s);scanf("%d",&k);
while(m<130)
{
	for(i=m,g=0;i<m+26;i++)
	{
		ch1[i]='a'+g++;
	}m+=26;
}
 m=0;
    while(m<130)
{
	for(i=m,g=0;i<m+26;i++)
	{
		ch2[i]='A'+g++;
	}m+=26;
}
for(i=0;i<n;i++)
{
	for(j=0;j<26;j++)
	{
		if(s[i]==ch1[j])
        {s[i]=ch1[j+k];j=26;}
        else if(s[i]==ch2[j])
            {s[i]=ch2[j+k];j=26;}
	}
}
    printf("%s",s);
    return 0;
}

Caesar Cipher Solution in Cpp

#include <iostream>
#include <string>
using namespace std;
int main() {
    int N = 0, K = 0;
    string str, dummy;
    cin >> N; getline(cin, dummy);
    getline(cin, str);
    cin >> K;
    int len = str.length();
    for (int i = 0; i < len; ++i)
        {
        if (65 <= str[i] && str[i] <= 90)
            str[i] = char(65 + ((str[i] - 65) + K) % 26);
        else if (97 <= str[i] && str[i] <= 122)
            str[i] = char(97 + ((str[i] - 97) + K) % 26);
    }       
    cout << str << endl;
    return 0;
}

Caesar Cipher Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int len = s.nextInt(); s.nextLine();
        String str = s.nextLine();
        int shift = s.nextInt();
        
        char sarr[] = str.toCharArray();
        for (int i=0; i<sarr.length; i++) {
            sarr[i] = cryptIt(sarr[i], shift);
        }
        System.out.println(new String(sarr));
    }
    
    public static char cryptIt(char c, int shift) {
        if (!Character.isAlphabetic(c)) return c;
        char base = 'A';
        if (c >= 'a') base = 'a';
        return (char)(((c - base + shift) % 26) + base);
    }
}
Ezoicreport this ad

Caesar Cipher Solution in Python

def ceasar(s,n):
    coded = []
    for el in s:
        if ord(el) >96 and ord(el) < 123:
            a = chr((ord(el)-97 +n) % 26+97)
            coded.append(a)
        elif ord(el) > 64 and ord(el) < 91:
            a = chr((ord(el)-65+n) % 26 + 65)
            coded.append(a)
        else:
            coded.append(el)
    return ''.join(coded)
l = int(raw_input())
s = raw_input()
n = int(raw_input())
print ceasar(s,n)

Caesar Cipher Solution using JavaScript

function processData(input) {
    //Enter your code here
    var lines = input.split('\n');
    var chars = parseInt(lines[0].trim(), 10);
    var text = lines[1].trim();
    var shift = parseInt(lines[2].trim(), 10)%26;
    var output = "";
    
    for(var i=0; i<chars; i++) {
        var character = text.charCodeAt(i);
        if (character >= 65 && character <= 90) {
            character += shift;
            if (character > 90) {
                character = 64 + (character - 90);
            }
        } else if (character >= 97 && character <= 122) {
            character += shift;
            if (character > 122) {
                character = 96 + (character - 122);
            }
        }
        output += String.fromCharCode(character);
    }
    
    process.stdout.write(output+"\n")
} 
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   processData(_input);
});

Caesar Cipher Solution in Scala

object Solution {
    def main(args: Array[String]) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
*/
        val len = readInt
        val s = readLine
        val k = readInt
        var result: String = ""
        for (i <- 0 to len - 1) {
          val item = s.charAt(i)
          if (item >= 'a' && item <= 'z') {
            result = result + ((item - 'a' + k) % 26 + 'a').asInstanceOf[Char].toString
          } else if (item >= 'A' && item <= 'Z') {
            result = result + ((item - 'A' + k) % 26 + 'A').asInstanceOf[Char].toString
          } else {
            result = result + item.toString
          }
        }
        println(result)
    }
}

Caesar Cipher Solution in Pascal

program caesar_cipher;
var big,small:set of Char;
    N,K,i:integer;
    S:string;
begin
    small:=['a'..'z'];
    big:=['A'..'Z'];
    readln(N);
    ReadLn(S);
    ReadLn(K);
    for i:=1 to N do
    begin
        if S[i] in small then
        begin
            if ord(S[i])+K > 122 then
                S[i]:=chr(ord('a')+((ord(S[i])+K-97) mod 26))
            else
                S[i]:=chr(ord(S[i])+K);
        end;
        if S[i] in big then
        begin
            if ord(S[i])+K > 90 then
                S[i]:=chr(ord('A')+((ord(S[i])+K-65) mod 26))
            else
                S[i]:=chr(ord(S[i])+K);
        end;
    end;
    Writeln(S);
end.  

Disclaimer: This problem (Caesar Cipher) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Two Characters Solution

Sharing Is Caring

Leave a Comment