Caesar Cipher

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
Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.

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



 is a valid ASCII string without any spaces.

Output Format

For each test case, print the encoded string.

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


public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String s = in.next();
        int k = in.nextInt();
        int m=0;
        int k1=0;
        String s1="";
        if(n>=1 && n<=100)m=n;
        if(s.length()<=n)s1=s;
        if(k>=0 && k<=100)k1=k;
       
        System.out.println(encrypt(s1,k1));
    }
    public static String encrypt(String s, int k){
        String str="";
        char c;
        int size=0;
        for(int i=0;i<s.length();i++){
            size=s.charAt(i);
            k = k%26;
            if(size>=97 && size<=122){
                size += k;
                if(size > 122){
                    size = size%122;
                    size += 96;
                }
                str+=(char)size;
            }else if(size>=65 && size<=90){
                size += k;
                if(size > 90){
                    size = size%90;
                    size += 64;
                }
                str+=(char)size;
            }else{
                str+=s.charAt(i);
            }
            //System.out.println(size+"-"+(char)size);
        }
        return str;
    }
}

Post a Comment

Previous Post Next Post