Caesar Cipher: Encryption | Hacker Rank Solution in Java 7

Problem:

Julius Caesar protected his confidential information by encrypting it in a cipher. Caesar's cipher rotated every letter in a string by a fixed number, , making it unreadable by his enemies. Given a string, , and a number, , encrypt  and print the resulting string.

Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.


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 {

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

    public static void main(String[] args) {
        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])?");

        scanner.close();
         k=k%26;
String x="";
int l=s.length();
for(int i=0;i<l;i++) {
    if((s.charAt(i)>=65 && s.charAt(i)<=90 )
     || (s.charAt(i)>=97 && s.charAt(i)<=122))

     {
         if((s.charAt(i)>=65 && s.charAt(i)<=90-k )
     || (s.charAt(i)>=97 && s.charAt(i)<=122-k))
     {

        x+=(char)(s.charAt(i)+k);
     }
else{
       x=x+(char)(s.charAt(i)+k-26);

     }
}
else
{
    x=x+s.charAt(i);
}
}  
System.out.println(x);

    }
}

Comments

Popular posts from this blog

Write a Function | Hacker Rank Solution in Python

Diagonal Difference | Hacker Rank Solution in C

Print Function | Hacker Rank Solution in Python