Caesar Cipher

  • + 0 comments

    Here is a Javascript solution

    function caesarCipher(s, k) {
        // Write your code here
        k = k % 26
        let encrypted =""
        
        for(let i =0; i < s.length; i++){
            let char  = s[i]
            
            // Check if the character is a letter
            if(char >= 'a' && char <= 'z'){
                // Shift lowercase letters
                let newChar = String.fromCharCode( ( (char.charCodeAt(0) - 97 + k) % 26) + 97)
                
                encrypted += newChar
            } else if(char >= 'A' && char <= 'Z'){
                let newChar = String.fromCharCode( ( (char.charCodeAt(0) - 65 + k) % 26) + 65)
                
                encrypted += newChar
            } else {
                encrypted += char
            }
        }
        return encrypted
    }