FRom hackerrank

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.
Original alphabet:      abcdefghijklmnopqrstuvwxyz
Alphabet rotated +3:    defghijklmnopqrstuvwxyzabc
For example, the given cleartext  and the alphabet is rotated by . The encrypted string is .
Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.

Solution in C# -

class Solution {
    static string caesarCipher(string s, int k) {
        char[] ch = s.ToCharArray();
        k = k%26;
        string ans = "";
        foreach(char c in ch)
        {
            if(char.IsLetter(c))
            {
                if(char.IsUpper(c))
                {
                    char tempc = (char)(c+k);
                    if(char.IsUpper(tempc))
                    ans = ans + tempc;
                    else
                    {
                        char cx = (char)(tempc - 26);
                        ans = ans + cx;
                    }    
                }
                else
                {
                    char tempc = (char)(c+k);
                    if(char.IsLower(tempc))
                    ans = ans + tempc;
                    else
                    {
                        char cx = (char)(tempc - 26);
                        ans = ans + cx;
                    }    
                }
            }
            else
                ans = ans + c;
        }
        return ans;
    }
    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        int n = Convert.ToInt32(Console.ReadLine());
        string s = Console.ReadLine();
        int k = Convert.ToInt32(Console.ReadLine());
        string result = caesarCipher(s, k);
        textWriter.WriteLine(result);
        textWriter.Flush();
        textWriter.Close();
    }
}

Post a Comment

Previous Post Next Post