Caesar Cipher

Sort by

recency

|

238 Discussions

|

  • + 0 comments

    a breath of fresh air from the confusing af tower breakers.

  • + 0 comments

    c++

    string caesarCipher(string s, int k) {
        std::string result;
    
        for(char c : s){
            if(c >= 'A' && c <= 'Z'){
                result += ('A') + (c - 'A' + k)%26;
            }
            else if(c >= 'a' && c <= 'z'){
                result +=  ('a') + (c - 'a' + k)%26;
            }
            else{
                result+=c;
            }
        }
        return result;
    }
    
  • + 0 comments

    C++

    string caesarCipher(string s, int k) {
        string alphabet = "abcdefghijklmnopqrstuvwxyz";
        int shift = k % alphabet.size(); // k % 26
        string rotated_alphabet = alphabet.substr(shift) 
                                + alphabet.substr(0, shift);
        
        string result;
        for (const char& c : s) {
            if (!std::isalpha(c)) {
                result += c;
            } else {
                char ec = rotated_alphabet[std::tolower(c) - 'a'];
    
                if (std::isupper(c)) {
                    ec = std::toupper(ec);
                }
                
                result += ec;            
            }
        }
        
        return result;
    }
    
  • + 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
    }
    
  • + 0 comments

    C++11

    string caesarCipher(string s, int k) {
    
        string enc = "";
        char salt = k % 26;
        int next;
    
        for (char c : s) {
      
            next = c + salt;
    
            if (c > 64 && c < 91) {
    
                c = next < 91 ? next : next - 26;
    
        
            } else if (c > 96 && c < 123) {
    
                c = next < 123 ? next : next - 26;
    
            }
    
            enc += c;
    
        }
        
        return enc;
    
    }