[Programmers / JAVA] Level 1 Caesar Cipher (12926)
[Programmers / JAVA] Level 1 Caesar Cipher (12926)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
An encryption method that shifts each letter of a sentence by a fixed distance to another letter is called a Caesar cipher. For example, shifting "AB" by 1 gives "BC", and shifting it by 3 gives "DE". Shifting "z" by 1 gives "a". Given a string s and a distance n, complete the function solution that creates the ciphertext obtained by shifting s by n.
- A space, no matter how much it is shifted, remains a space.
- s consists only of lowercase letters, uppercase letters, and spaces.
- The length of s is 8000 or less.
- n is a natural number between 1 and 25, inclusive.
| s | n | result |
|---|---|---|
| "AB" | 1 | "BC" |
| "z" | 1 | "a" |
| "a B z" | 4 | "e F d" |
Shift the characters of the given string s by n to create the Caesar cipher. For a lowercase z, shifting it once wraps around to a, and likewise an uppercase Z shifted once wraps around to A. A space stays a space no matter how many times it is shifted.
We just need to appropriately cycle each character by the given number and return the resulting string. We can make use of each character's ASCII code number.
- A ~ Z: 65 ~ 90
- a ~ z: 97 ~ 122
When the shift goes beyond that range, let's create a method that wraps around to the start of the range and returns that code.
JAVA
private int converter(int num, int n) { // If uppercase if (num >= 65 && num <= 90) { // If it goes beyond the uppercase range if (num + n > 90) { return num + n - 90 + 65 - 1; } return num + n; } // If lowercase else if (num >= 97 && num <= 122) { // If it goes beyond the lowercase range if (num + n > 122) { return num + n - 122 + 97 - 1; } return num + n; } // If it's a space else { return ' '; } }
The converter method takes the given number and the shift amount and returns the shifted number. For a space, it simply returns a space right away without shifting.
JAVA
import java.util.stream.Collectors; /** * Caesar Cipher class * * @author RWB * @since 2021.12.13 Mon 16:12:50 */ class Solution { /** * Method that returns the answer * * @param s: [String] string * @param n: [int] shift distance * * @return [String] answer */ public String solution(String s, int n) { return s.chars().mapToObj(value -> Character.toString(converter(value, n))).collect(Collectors.joining("")); } /** * Method that returns the conversion result * * @param num: [int] original number * @param n: [int] shift distance * * @return [int] converted number */ private int converter(int num, int n) { // If uppercase if (num >= 65 && num <= 90) { // If it goes beyond the uppercase range if (num + n > 90) { return num + n - 90 + 65 - 1; } return num + n; } // If lowercase else if (num >= 97 && num <= 122) { // If it goes beyond the lowercase range if (num + n > 122) { return num + n - 122 + 97 - 1; } return num + n; } // If it's a space else { return ' '; } } }
