Header Ad

HackerRank Caesar Cipher problem solution

In this HackerRank Caesar Cipher problem, you need to rotate the string by 3 shifts. and in the case of a rotation by 3, w, x, y, and z would map to z, a, b and c.

HackerRank Caesar Cipher problem solution


Problem solution in Python programming.

N = int(input())
string = list(input())
addNum = int(input())

length = len(string)
for i in range(length):
	if ord(string[i]) <= ord("Z") and ord(string[i]) >= ord("A"):
		asciiCode = ord(string[i]) + addNum
		while asciiCode > ord("Z"):
			asciiCode = asciiCode - ord("Z") + ord("A") - 1
		string[i] = chr(asciiCode)
	elif ord(string[i]) <= ord("z") and ord(string[i]) >= ord("a"):
		asciiCode = ord(string[i]) + addNum
		while asciiCode > ord("z"):
			asciiCode = asciiCode - ord("z") + ord("a") - 1
		string[i] = chr(asciiCode)

print("".join(string))


Problem solution in Java Programming.

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

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.nextLine();
        String input = scanner.nextLine();
        int k = scanner.nextInt();
        
        StringBuilder builder = new StringBuilder(input.length());
        for (int i = 0; i < n; i++) {
            char temp = input.charAt(i);
            boolean upperCase = Character.isUpperCase(temp);
            if (Character.isLetter(temp)) {
                temp += k%26;
                if (!Character.isLetter(temp) || (upperCase && !Character.isUpperCase(temp))) {
                    temp -= 26;
                }
            }
            builder.append(temp);
        }
        
        System.out.println(builder.toString());
    }
}


Problem solution in C++ programming.

#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 n;
       char s[100];
       int k;
    cin >> n;
    for (int i =0; i < n;i++){
        cin>> s[i];
    }
    cin >> k;
    for (int i =0; i<n;i++)
        {
        if((s[i]>='a' && s[i]<='z')){
            char o = s[i]- 'a' + k;
                 o = o %('z'-'a' +1);
                 o+='a';
            cout<<o;
        }
        else if ((s[i]>='A' && s[i]<='Z')){
            char o = s[i] - 'A' + k;
                 o = o %('Z'-'A'+1);
                 o+='A';
            cout<<o;
        }
          else
           cout <<s[i];
                            
    }
    
    return 0;
}


Problem solution in C programming.

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

int main() {
    int i;
    int n;
    char s[101];
    int k;
    scanf("%d %s %d", &n, s, &k);
    k %= 26;
    for (i=0; i<n; i++) {
        if ((s[i] >= 'A') && (s[i] <= 'Z')) {
            if ((s[i]+k >= 'A') && (s[i]+k <= 'Z'))
                printf("%c", s[i]+k);
            else
                printf("%c", 'A'+(((s[i])+k)-'Z')-1);
        }
        else {
            if ((s[i] >= 'a') && (s[i] <= 'z'))
                if (((s[i])+k >= 'a') && ((s[i])+k <= 'z'))
                    printf("%c", (s[i])+k);
                else
                    printf("%c", 'a'+(((s[i])+k)-'z')-1);
            else
                printf("%c", s[i]);
        }
    }
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    //Enter your code here
    var lines = input.split("\n");
    var L = parseInt(lines[0]);
    var message = lines[1].split("");
    var n = parseInt(lines[2]) % 26;
    var newcode = "";
    
    for (var i = 0; i < L; i++){
        //if the character is a valid letter, increase the charcode by n, and get the letter back, 
        //if it's between 65-90 or 97-122.
        var code = message[i].charCodeAt(0);
        if(65 <= code && code <= 90){
            newcode = code + (code + n > 90 ? n - 26 : n);
            message[i] = String.fromCharCode(newcode);
        }
        else if(97 <= code && code <= 122){
            newcode = code + (code + n > 122 ? n - 26 : n);
            message[i] = String.fromCharCode(newcode);
        }
        else{
            //skip it.
        }
    }
    
    console.log(message.join("").toString());
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});


Post a Comment

2 Comments

  1. using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using System.Collections;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.Serialization;
    using System.Text.RegularExpressions;
    using System.Text;
    using System;

    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)
    {
    int count = 0;
    int z = 0;
    string nextChar = "";
    char[] charArray = s.ToCharArray();
    foreach (char c in charArray)
    {
    count = (int)c;
    if (((int)c >= 65 && (int)c <= 90) || ((int)c >= 97 && (int)c <= 122))
    {
    k = k % 26;
    // count = ((int)c) + k;
    if ((int)c >=65 && (int)c <=90)
    {
    count= 65 + (((int)c - 65) +k )% 26 ;
    }
    else if ((int)c >=97 && (int)c <=122)
    {
    count = 97 + (((int)c - 97) + k) % 26;
    }
    nextChar += Convert.ToString((char)(count));
    }
    else
    {
    nextChar += Convert.ToString((char)(count));

    }

    }


    return nextChar;
    }

    }

    class Solution
    {
    public static void Main(string[] args)
    {
    //TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

    int n = Convert.ToInt32(Console.ReadLine().Trim());

    string s = Console.ReadLine();

    int k = Convert.ToInt32(Console.ReadLine().Trim());

    string result = Result.caesarCipher(s, k);

    Console.WriteLine(result);
    Console.ReadKey();

    //textWriter.Flush();
    //textWriter.Close();
    }
    }

    ReplyDelete