I was working on straightforward encryption and got stuck on one of its rules.
The rules are,
- Encryption work by adding 5 to each character.
- Only encrypt
a-z
andA-Z
, all other characters will add to the encrypted string as it is. - If the character is
z
orZ
, the adding starts from the charactera
. - By performing the above encryption in reverse, the description should also be present.
I was able to do the encryption, but the 3rd rule is where I got stuck when decrypting.
Below is the code I tried,
# Encrypt
Input : Dinindu-12Z
Output : Insnsiz-12F
# Decrypt
Input : Insnsiz-12F
Output : Dinindu-12Z # This is the expected output, but got "Dinind\-12A"
using System;
class Program
{
public static String encrypt(String input)
{
String output = "";
foreach (char c in input)
{
if (char.IsLetter(c))
{
char cc = c;
if (c == 'z') cc = 'a';
if (c == 'Z') cc = 'A';
output += (char)(((int)cc) + 5);
}
else
{
output += c;
}
}
return output;
}
public static string decrypt(String input)
{
String output = "";
foreach (char c in input)
{
if (char.IsLetter(c))
{
char cc = c;
if (c == 'z') cc = 'a';
if (c == 'Z') cc = 'A';
output += (char)(((int)cc) - 5);
}
else
{
output += c;
}
}
return output;
}
public static void Main(string[] args)
{
String a = encrypt("Dinindu-12Z");
String b = decrypt(a);
Console.WriteLine(a);
Console.WriteLine(b);
}
}