Caesar Cipher

Sort by

recency

|

241 Discussions

|

  • + 0 comments
    def caesarCipher(s, k):
        # Write your code here
        encrypted = []
        for char in s:
            if char.isalpha():
                if char.islower():
                    new_char = chr(((ord(char)-ord('a')+k)%26)+ord('a'))
                elif char.isupper():
                    new_char = chr(((ord(char)-ord('A')+k)%26)+ord('A'))
                encrypted.append(new_char)
            else:
                encrypted.append(char)
        return ''.join(encrypted)
    
  • + 0 comments

    Python3

    alphabet = "abcdefghijklmnopqrstuvwxyz"
    alphabet_cap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    encrypted = ""
    
    #calculate new k if k is greater than 26
    if k > 26:
        k = k % 26
    
    #rotate alphabet by k
    rotated_alphabet = alphabet[k:] + alphabet[:k]
    rotated_alphabet_cap = alphabet_cap[k:] + alphabet_cap[:k]
    
    
    #encrypt
    for i in range(len(s)):
    
        #uppercase letters
        if s[i].isupper():
            index = alphabet_cap.index(s[i])
            encrypted += rotated_alphabet_cap[index]
    
        #lowercase letters
        elif s[i].islower():
            index = alphabet.index(s[i])
            encrypted += rotated_alphabet[index]
    
        #punctuation, hyphens, etc
        else:
            encrypted += s[i]
    
    return encrypted
    
  • + 0 comments

    Kotlin Solution

    fun caesarCipher(s: String, k: Int): String {
        return buildString{
            s.map{ letter ->
                when {
                    letter in 'a'..'z' -> append('a' + (letter - 'a' + k) % 26) 
                    letter in 'A'..'Z' -> append('A' + (letter - 'A' + k) % 26) 
                    else -> append(letter)
                }
            }
        }
    }
    
  • + 0 comments

    a breath of fresh air from the confusing af tower breakers.

  • + 0 comments

    c++

    string caesarCipher(string s, int k) {
        std::string result;
    
        for(char c : s){
            if(c >= 'A' && c <= 'Z'){
                result += ('A') + (c - 'A' + k)%26;
            }
            else if(c >= 'a' && c <= 'z'){
                result +=  ('a') + (c - 'a' + k)%26;
            }
            else{
                result+=c;
            }
        }
        return result;
    }