Caesar Cipher HackerRank Solution in C, C++, Java, Python

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:      abcdefghijklmnopqrstuvwxyz

Alphabet rotated +3:    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-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, , the length of the unencrypted string.

The second line contains the unencrypted string, .

The third line contains , 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

Caesar Cipher HackerRank Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int n,i,j,k;
    char ar[101];
    unsigned char x;
    scanf("%d",&n);
    scanf("%s",ar);
    scanf("%d",&k);
    for(i=0;i<n;i++)
    {
        x=ar[i];
        if(x>=97 && x<=122)
        {
            x=x+(k%26);
            if(x>122)
            {
                x=96+(x-122);
            }
            ar[i]=x;
        }
        else if(x>=65 && x<=90)
        {
            x=x+(k%26);
            if(x>90)
            {
                x=64+(x-90);
            }
            ar[i]=x;
        }
    }
    printf("%s",ar);
    return 0;
}

 

Caesar Cipher HackerRank Solution in C++

#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 HackerRank 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);
    }
}

 

Caesar Cipher HackerRank Solution in Python

import sys

INDEX_TABLE = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
raw_alphabet = 'abcdefghijklmnopqrstuvwxyz'

sys.stdin.readline()
to_encode = sys.stdin.readline()
shift_amount = int(sys.stdin.readline()) % 26

encoded_alphabet = raw_alphabet[shift_amount:] + raw_alphabet[0:shift_amount]
# print encoded_alphabet
result_str = ''
for ch in to_encode:
    is_upper = ch.isupper()
    ch = ch.lower()
    if ch in INDEX_TABLE:
        if is_upper:
            result_str += encoded_alphabet[INDEX_TABLE[ch]].upper()
        else:
            result_str += encoded_alphabet[INDEX_TABLE[ch]]
    else:
        result_str += ch
print result_str

 

Caesar Cipher HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        var length = int.Parse(Console.ReadLine());
        var s = Console.ReadLine();
        var k = int.Parse(Console.ReadLine());
        
        foreach (var c in s)
        {
            if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
            {
                Console.Write(c);
            }
            else
            {
                var isLower = (c >= 'a' && c <= 'z');
                
                var c1 = c.ToString().ToLower()[0];
                
                c1 += (char)(k % 26);
                
                if (c1 > 'z')
                {
                    c1 -= (char)26;
                }
                
                if (!isLower)
                {
                    c1 = c1.ToString().ToUpper()[0];
                }
                
                Console.Write(c1);
            }
        }
        
        Console.WriteLine();
    }
}

 

Attempt Caesar Cipher HackerRank Challenge

Link – https://www.hackerrank.com/challenges/caesar-cipher-1/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/mars-exploration-hackerrank-solution/

Leave a Comment