Sort by

recency

|

1267 Discussions

|

  • + 0 comments

    Simple Java Solution:

    public static String caesarCipher(String s, int k) {
        k = k % 26; // Reduce k to avoid unnecessary shifts
        StringBuilder sb = new StringBuilder();
    
        for (char c : s.toCharArray()) { // Use char directly for simplicity
            if (c >= 'A' && c <= 'Z') { // Uppercase letters
                sb.append((char) ('A' + (c - 'A' + k) % 26));
            } else if (c >= 'a' && c <= 'z') { // Lowercase letters
                sb.append((char) ('a' + (c - 'a' + k) % 26));
            } else { // Non-alphabetic characters
                sb.append(c);
            }
        }
    
        return sb.toString();
    }
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/KApgpiqqX20

    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
       string s;
       int cipher;
       cin >> cipher;
       cin >> s;
       cin >> cipher;
       for(char &c:s) {
           if(isalpha(c)){
               char a = isupper(c)? 'A':'a';
               c = a + (c - a + cipher) % 26;
           }
       }
        cout << s ;
        return 0;
    }
    
  • + 0 comments
    def caesarCipher(s, k):
        ans = ''
        k = k % 26 
        for i in s:
            if i.islower():
                ans += chr(((ord(i) - ord('a') + k) % 26) + ord('a'))
            elif i.isupper():
                ans += chr(((ord(i) - ord('A') + k) % 26) + ord('A'))
            else:
                ans += i 
        return ans
    
  • + 0 comments
    def caesarCipher2(s, k):
        k = k % 26
        for i in s:
            if 97 <= ord(i) <= 122:
                res.append(chr(ind if (ind:=ord(i) + k) <= 122 else ind - 26))
            elif 65 <= ord(i) <= 90:
                res.append(chr(ind if (ind := ord(i) + k) <= 90 else ind - 26))
            else:
                res.append(i)
    
  • + 0 comments

    Java solution:

     public static boolean isLower(char c){
            return c >= 97 && c <= 122;
            }
        public static boolean isUpper(char c){
            return c >= 65 && c <= 90;
            }
       
       
        public static String caesarCipher(String s, int k) {
            String encrypted_text = "";
            int n = s.length();
            
            for(int i = 0; i < n; i++){
                char c = s.charAt(i);
                if(isUpper(c))
                    c = (char)( ( ( ( (int)c - 65) + k) % 26) + 65) ;
                else if(isLower(c))
                    c = (char)( ( ( ( (int)c - 97) + k) % 26) + 97) ;
                
                
                encrypted_text += c;
                }
            return encrypted_text;
    
            }