Caesar Cipher

Sort by

recency

|

584 Discussions

|

  • + 0 comments

    js single line code solution:

    const caesarCipher = (s, k) => (String.fromCodePoint(...[...s].map((char,idx,arr,currCodePoint)=>(currCodePoint = char.codePointAt(0),(currCodePoint<=90&&currCodePoint>=65)?(((currCodePoint + k)-65)%26+65):((currCodePoint<=122&&currCodePoint>=97)?(((currCodePoint + k)-97)%26+97):(currCodePoint))))));
    
  • + 0 comments
    def caesarCipher(s, k):
    low='abcdefghijklmnopqrstuvwxyz'
    up= low.upper()
    new=''
    
    for i in s:
        if i in low:
            real_r= (low.index(i)+k)%26
            new+= low[real_r]
        elif i in up:
            real_r= (up.index(i)+k)%26
            new+= up[real_r]
        else:
            new+= i
    return new
    
  • + 0 comments
    def caesarCipher(s, k):
            alphabet = "abcdefghijklmnopqrstuvwxyz"
            res = ""
            for c in s:
                    is_upper = c.isupper()
                    idx = alphabet.find(c.lower())
                    if idx != -1:
                            new_idx = (idx + k) % 26
                            res += alphabet[new_idx].upper() if is_upper else alphabet[new_idx]
                    else:
                            res += c
    
            return res
    
  • + 0 comments

    did it using ascii value in Java public static String caesarCipher(String s, int k) { String s1 = ""; int k1;

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
            k1 = k;
    
            while (k1 > 0) {
                if (Character.isLowerCase(c) && c + k1 <= 'z') {
                    c = (char) (c + k1);
                    break;
                } else if (Character.isLowerCase(c) && c + k1 > 'z') {
                    k1 -= ('z' - c + 1);  
                    c = 'a';  
                } else if (Character.isUpperCase(c) && c + k1 <= 'Z') {
                    c = (char) (c + k1);
                    break;
                } else if (Character.isUpperCase(c) && c + k1 > 'Z') {
                    k1 -= ('Z' - c + 1); 
                    c = 'A'; 
                }
            }
    
            s1 += c;
        } else {
            s1 += c; 
        }
    }
    
    return s1;
    

    }

  • + 0 comments

    def shiftLetter(ch, shift): sub_const = ord('z') - ord('a') + 1 shift = shift % 26 numval = ord(ch)+shift
    upper = ch.isupper()

    if upper:  # case it's uppercase
        if numval > ord('Z'):  # check if have to reset to 1
            numval = numval - sub_const
    else:  # case it's lowercase
        if numval > ord('z'):
            numval = numval -  sub_const
    return chr(numval)
    

    def caesarCipher(s, k): # Write your code here new_s = str() for c in s: if c.isalpha(): ch = shiftLetter(c, k) else: #non alpha chars ch = c new_s += ch return new_s