-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesarCipher.java
50 lines (43 loc) · 1.49 KB
/
CaesarCipher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
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, K, making
it unreadable by his enemies. Given a string, S, and
a number, K, encrypt S and print the resulting string.
Note: The cipher only encrypts letters; symbols, such
as -, remain unencrypted.
Link: https://www.hackerrank.com/challenges/caesar-cipher-1
*/
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 in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
int k = in.nextInt();
String code = cipher(s, k);
System.out.println(code);
}
public static String cipher(String str, int k) {
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (Character.isLetter(c) && Character.isUpperCase(c)) {
int value = (int) c;
value -= 65;
value = (value + k) % 26;
sb.setCharAt(i, (char)(value + 65));
}else if (Character.isLetter(c) && Character.isLowerCase(c)) {
int value = (int) c;
value -= 97;
value = (value + k) % 26;
sb.setCharAt(i, (char)(value + 97));
}
}
return sb.toString();
}
}