• + 0 comments

    Simple Java Solution:

    public static String caesarCipher(String s, int k) {
        k = k % 26; // Reduce k to avoid unnecessary shifts
        StringBuilder sb = new StringBuilder();
    
        for (char c : s.toCharArray()) { // Use char directly for simplicity
            if (c >= 'A' && c <= 'Z') { // Uppercase letters
                sb.append((char) ('A' + (c - 'A' + k) % 26));
            } else if (c >= 'a' && c <= 'z') { // Lowercase letters
                sb.append((char) ('a' + (c - 'a' + k) % 26));
            } else { // Non-alphabetic characters
                sb.append(c);
            }
        }
    
        return sb.toString();
    }