Caesar Cipher

Sort by

recency

|

121 Discussions

|

  • + 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
    
  • + 0 comments
    def caesarCipher(s, k):
        # Write your code here
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        k = k % 26
        alphabet_rot = alphabet[k:] + alphabet[:k]
        result = []
        for i in range(len(s)):
            for idx, char in enumerate(alphabet):
                if s[i] == char:
                    result.append(alphabet_rot[idx])
                elif s[i] == char.upper():
                    result.append(alphabet_rot[idx].upper())
            if s[i].isalpha() == False:
                result.insert(i, s[i])
        return ''.join(result)