Caesar Cipher

Sort by

recency

|

122 Discussions

|

  • + 0 comments

    Python 3:

    def caesarCipher(s: str, k: int) -> str:
        k = k % 26
        rotated = ascii_lowercase[k:] + ascii_lowercase[:k]
        return s.translate(
            str.maketrans(
                dict(zip(ascii_letters, f"{rotated}{rotated.upper()}", strict=True))
            )
        )
    
  • + 0 comments

    Java solution:

    public static String caesarCipher(String s, int k) {
    
      char[] chars = s.toCharArray();
      for(int i=0; i<chars.length;i++){ 
          if (chars[i]-'a'>=0 && chars[i]-'a'<26) 
              chars[i]=(char)((chars[i]-'a'+k)%26+'a');                      
          else if (chars[i]-'A'>=0 && chars[i]-'A'<26) 
              chars[i]=(char)((chars[i]-'A'+k)%26+'A');          
    
      }
      return String.valueOf(chars);
    }
    
  • + 0 comments
    def cypher(k):
            def mapper(c):
                    if not c.isalpha():
                            return c
                    n_letters = 26
                    a = ord('A') if c.isupper() else ord('a')
                    c = ord(c)
                    new_c = ((c - a + k) % n_letters) + a
                    return chr(new_c)
    return mapper
    
    def caesarCipher(s, k):
        return "".join(map(cypher(k), [x for x in s]))
    

    k): # Write your code here return "".join(map(cypher(k), [x for x in s])

  • + 0 comments

    My rust solution:

    fn caesarCipher(s: &str, k: u8) -> String {
        s.bytes()
            .map(|b| {
                if b.is_ascii_alphabetic() {
                    let first_letter = if b.is_ascii_lowercase() { b'a' } else { b'A' };
                    char::from((((b - first_letter) + k) % 26) + first_letter).to_string()
                } else {
                    char::from(b).to_string()
                }
            })
            .collect::<Vec<String>>()
            .join("")
    }
    
  • + 0 comments
    def caesarCipher(s, k):
        # Write your code here
        rotator = k % 26
        answer = ""
        for item in s:
            temp = item
            if item.isalpha():
                curr = ord(item) + rotator
                ascii_value = 0
                if item.isupper():
                    ascii_value = int(curr-26) if curr > ord('Z') else curr
                elif item.islower():
                    ascii_value = int(curr-26) if curr > ord('z') else curr
                temp = chr(ascii_value)
            answer += temp
        return answer