Source : https://www.hackerrank.com/challenges/caesar-cipher-1
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: abcdefghijklmnopqrstuvwxyzAlphabet rotated +3: defghijklmnopqrstuvwxyzabc
For example, the given cleartext and the alphabet is rotated by . The encrypted string is .
Note: The cipher only encrypts letters; symbols, such as -
, remain unencrypted.
Function Description
Complete the caesarCipher function in the editor below. It should return the encrypted string.
caesarCipher has the following parameter(s):
- s: a string in cleartext
- k: an integer, the alphabet rotation factor
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: abcdefghijklmnopqrstuvwxyzAlphabet rotated +2: cdefghijklmnopqrstuvwxyzabm -> oi -> kd -> fd -> fl -> ne -> g- -O -> Qu -> wt -> vz -> b
Source : https://www.hackerrank.com/challenges/caesar-cipher-1
Solution
// Karthikalapati.blogspot.com | |
static String caesarCipher(String str, int k) { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < str.length(); i++) { | |
char ch = str.charAt(i); | |
sb.append(encrypt(ch, k)); | |
} | |
return sb.toString(); | |
} | |
/* Encrypts a character using Caesar Cipher */ | |
private static char encrypt(char ch, int K) { | |
if (!Character.isLetter(ch)) { | |
return ch; | |
} | |
char base = Character.isLowerCase(ch) ? 'a' : 'A'; | |
return (char) ((ch - base + K) % 26 + base); | |
} | |
// Discuss on HackerRank: https://www.hackerrank.com/challenges/caesar-cipher-1/forum/comments/269393 |
No comments:
Post a Comment