Caesar Cipher

Sort by

recency

|

614 Discussions

|

  • + 0 comments

    def caesarCipher(s, k): # Write your code here alphabet = 'abcdefghijklmnopqrstuvwxyz' alphabet = ''.join([letter + letter.upper() for letter in alphabet]) result = ''

    for i in range(len(s)):
        if s[i] not in alphabet:
            result += s[i]
        else:
            result += alphabet[(alphabet.index(s[i])+(k*2))%len(alphabet)]
    
    return result
    
  • + 0 comments
    public static String caesarCipher(String s, int k) {
            StringBuilder res = new StringBuilder();
            k %= 26;
            
            for(char c : s.toCharArray()){
                if(c >= 'a' && c <= 'z'){
                    c += k;
                    c %= 'z' + 1;
                    c += c < 'a' ? 'a' : 0;  
                }
                
                if(c >= 'A' && c <= 'Z'){
                    c += k;
                    c %= 'Z' + 1;
                    c += c < 'A' ? 'A' : 0;  
                }
                
                res.append(c);
            }
            
            return res.toString();
        }
            
            return res;
        }
    
  • + 0 comments

    Java with explain.

    String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //26+26 symbols
            String result = "";
            k = k % 26;//correct rotate amount
            for (int i = 0; i < s.length(); i++) {
                Character currentChar = s.charAt(i);
                int index = alphabet.indexOf(currentChar); //get index of char
                if (index < 26 && index + k > 25 //correct index if it goes abroad
                        || index < 52 && index + k > 51) { //for uppercase
                    index -= 26;
                }
                if (Character.isLetter(currentChar)) { //if it not a char (-' e.t.c)
                    result = result + alphabet.charAt(index + k);
                } else {
                    result = result + s.charAt(i);
                }
            }
            return result;
    
  • + 0 comments
    def caesarCipher(s, k):
        # Write your code here
        return "".join([chr(((ord(char) + (k % 26) - 97) % 26) + 97) if char.islower() else chr(((ord(char) + (k % 26) - 65) % 26) + 65) if char.isalpha() else char for char in s])
    
  • + 0 comments

    Scala solution

    def caesarCipher(s: String, k: Int): String = {
        // Write your code here
            val shift = k % 26
            s.map {char => if (char.isLower){((char - 'a' + shift) % 26 + 'a').toChar}
            else if (char.isUpper){((char - 'A' + shift) % 26 + 'A').toChar}
            else {char}}.mkString
    
        }