Caesar Cipher

Sort by

recency

|

607 Discussions

|

  • + 0 comments
    def caesarCipher(s, k):
        # Write your code here
    
        k = k - ((k//26) * 26)    # normalising the K
        cipher = ""
        for i in range(len(s)):
            if 64 < ord(s[i]) < 91 :
                val = ord(s[i]) + k if (ord(s[i]) + k) < 91 else 64 + (ord(s[i]) + k) - 90
                cipher = cipher + chr(val)
            elif 96 < ord(s[i]) < 123 :
                val = ord(s[i]) + k if (ord(s[i]) + k) < 123 else 96 + (ord(s[i]) + k) - 122
                cipher = cipher + chr(val)
            else :
                val = ord(s[i])
                cipher = cipher + chr(val)   
        return cipher
    
  • + 0 comments
    def caesarCipher(s, k):
        res=""
        for i in range(len(s)):
            small, ch = check('a','z', s, i, k)
            if not small:
                big, ch = check('A', 'Z', s, i, k)
            res+=ch
        return res
    
    def check(start, end, s, i,  k):
        n = ord(end)-ord(start)+1
        ch = s[i]
        if ord(start) <= ord(ch) <= ord(end):
            i = ord(ch) - ord(start)
            new_i = (i + k) % n
            return True, chr(ord(start) + new_i)
        return False, ch
    
  • + 0 comments

    Simplified Java Solution Method:

    public static String caesarCipher(String s, int k) {
        // Write your code here
            String cipher = "";
            k%=26;
                    
            for(char c : s.toCharArray()){
                if(Character.isLetter(c)){
                    if((Character.isUpperCase(c)&&(c+k)>90)||(Character.isLowerCase(c)&&(c+k)>122)){
                         c-=26;                  
                    }
                    c+=k;
                }
                cipher+=c;   
            }
            return cipher;
        }
    
  • + 0 comments

    def caesarCipher(s, k): # Write your code here k %= 26 cyphStr = "" lAlph = "abcdefghijklmnopqrstuvwxyz" uAlph = lAlph.upper()

    lAlph = lAlph[k:] + lAlph[:k]
    uAlph = uAlph[k:] + uAlph[:k]
    
    for c in s:
        if 'a' <= c <= 'z':
            charASCII = (ord(c) - ord('a'))%26
            cyphStr += lAlph[charASCII]
        elif 'A' <= c <= 'Z':
            charASCII = (ord(c) - ord('A'))%26
            cyphStr += uAlph[charASCII]
        else:
            cyphStr += c
    
    
    return cyphStr
    
  • + 0 comments

    If you are failing 3 cases you need to consider if the uppercase letters went into lowercase letters.