# Caesar Cipher HackerRank Solution In Java.

Hello Programmers,

Today I will give you the solution of hackerrank problem which is Caesar Cipher.  In this problem, we need to shifts each letter by a number of letters.

## Question:

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.

For example, the given cleartext s= "middle-Outz" and the alphabet is rotated by k=2.
The encrypted string is okffng-Qwvb.

Example:

Original alphabet: abcdefghijklmnopqrstuvwxyz
Alphabet rotated +3: defghijklmnopqrstuvwxyzabc

### Solution:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

// Complete the caesar cipher function below.
static String caesar cipher(String s, int k) {

k=k%26; // we do this because to do short the value of k.

StringBuilder sb=new StringBuilder(s);

for(int i=0;i<sb.length();i++)
{
int ch=s.charAt(i);
if(ch>=97 && ch<=122)
{
int num=ch+k;
if(num>122)
{
// we do this to get back the counting start from starting after alphabet is complete.
num=96+num-122;
}
//change the character
sb.setCharAt(i,(char)num);
}
else if(ch>=65 && ch<=90)
{
int num=ch+k;
if(num>90)
{
num=64+num-90;
}
sb.setCharAt(i, (char)num);
}
}
return (sb.toString());
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

String s = scanner.nextLine();

int k = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

String result = caesarCipher(s, k);

bufferedWriter.write(result);
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}