【问题标题】:C# Ceasar cipher problem with negative numbers带有负数的 C# Ceasar 密码问题
【发布时间】:2022-01-01 07:57:41
【问题描述】:

所以基本上代码对于某些输入工作正常,但我想要 input "abcdefghijklmnopqrstuvwxyz" 然后作为位置 "-3" ,预期输出应该是 "xyzabcdefghijklmnopqrstuvw",有人可以帮忙吗?

            Console.WriteLine("Type a string to encrypt:");
            string UserString = Console.ReadLine();

            Console.WriteLine("\n");

            Console.Write("Type in the position:");
            int key = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\n");


            Console.WriteLine("Encrypted Data");

            string cipherText = Encipher(UserString, key);
            Console.WriteLine(cipherText);
            Console.Write("\n");

            char cipher(char ch, int key)
            {
                if (!char.IsLetter(ch))
                {

                    return ch;
                }

                char d = char.IsUpper(ch) ? 'A' : 'a';
                return (char)((((ch + key) - d) % 26) + d);

            }

            string Encipher(string input, int key)
            {
                string output = string.Empty;

                foreach (char ch in input)
                    output += cipher(ch, key);

                return output;
            }

【问题讨论】:

    标签: c# algorithm


    【解决方案1】:

    如果你想使用任何任意数,你应该使用一点详细的余数

     result = (source % mod + mod) % mod;
    

    在我们的例子中(mod == 26)我们将有(我把key % 26 而不是只是key 为了在巨大的情况下不出现整数溢出 key,例如key = int.MaxValue):

    static char cipher(char ch, int key) {
      if (ch >= 'a' && ch <= 'z')
        return (char)('a' + ((ch - 'a' + key % 26) % 26 + 26) % 26);
      else if (ch >= 'A' && ch <= 'Z')
        return (char)('A' + ((ch - 'A' + key % 26) % 26 + 26) % 26);
    
      return ch;
    }
    

    那你就可以放(我们用Linq

    string Encipher(string input, int key) => 
      string.Concat(input.Select(c => cipher(c, key)));
    
    // Same as Encipher, but with negative key: note -key 
    string Decipher(string input, int key) => 
      string.Concat(input.Select(c => cipher(c, -key)));
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2020-02-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多