Caesar Cipher
Problem
Read a word and a shift k (a non-negative integer). Move every English letter k places forward in the alphabet. Z goes back to A. Keep the case. Keep every other character as it is.
Constraints
- 1 <= length <= 1000
- 0 <= k <= 10^9
Examples
Input
Hello 3
Output
Khoor
Solutions
Subtract the base letter to get a position 0-25, add the shift, wrap with % 26, then add the base again. The shift can be larger than 26, so reduce it first.
/*
* Problem : Shift letters.
* Input : A word and a shift.
* Output : The shifted word.
* Approach: Alphabet arithmetic.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String a, String b) {
// Step 1: The shift arrives as text. Convert it to a number. Only the remainder after 26 matters.
int shift = (int) (Long.parseLong(b) % 26);
StringBuilder result = new StringBuilder();
for (int i = 0; i < a.length(); i++) {
char letter = a.charAt(i);
// Step 2: Move a letter inside its own range (A-Z or a-z). Use the first letter of the range as the base.
if (letter >= 'A' && letter <= 'Z') {
result.append((char) ('A' + (letter - 'A' + shift) % 26));
} else if (letter >= 'a' && letter <= 'z') {
result.append((char) ('a' + (letter - 'a' + shift) % 26));
} else {
// Step 3: Other characters stay the same.
result.append(letter);
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (1)
- What does a shift of 26 do?