Advanced Version of the Caesar Cipher


Submit solution

Points: 20
Time limit: 1.0s
Memory limit: 64M

Author:
Problem type

題目說明

<1122檢定考題>
凱撒密碼(Caesar Cipher)是一種簡單的替換式加密方法,
其中每個英文字母都透過一定的偏移量替換成另一個英文字母。
例如,當替換規則為向後移動3個位置時(稱之偏移量為3),
此時字母A將被替換為字母D,字母B將被替換為字母E,而字母Z則替換成字母C (Z的下一個字母是A、z的下一個字母是a)。
但非字母字元(如數字和符號)則不用進行偏移量處理。
此外,本題是進階版的凱撒密碼,所以要求對每個字進行Caesar Cipher加密後再加以反轉。
即"HELLO"經過凱撒密碼加密(假如偏移是3)為"KHOOR",然後再經反轉為"ROOHK"。

請撰寫一個進階版Caesar Cipher加密功能的Java程式。讓使用者輸入包含多個字的字串,並輸出加密後的密文(Cipher text)。

說明

在本題中以空格隔開的字串視為一個字。
舉例來說,"I   got   Covid-19."有3個字,包含:"I"、"got"、"Covid-19."。所以"I   got   Covid-19."、偏移量3的加密步驟如下:

  • 對"I   got   Covid-19." 進行偏移量3處理,得到"L   jrw   Frylg-19."
  • 再"L   jrw   Frylg-19."進行個別字的反轉,得到"L   wrj   .91-glyrF"
  • 輸出密文"L   wrj   .91-glyrF"

輸入

  • 第一行是讓使用者輸入一行欲加密的字串。
  • 第二行則是讓使用者輸入一個整數N,代表加密的偏移量。

輸出

加密後的密文

sample input & output

輸入 輸出
樣本1 Hello   World.
3
roohK   .gourZ
樣本2 IT   is   17:00
3
WL   vl   00:71
樣本3 XYZ   xyz   123~4567
2
BAZ   baz   7654~321
樣本4 Let's meet at the usual place tomorrow at 1 PM.
27
t'ufM uffn ub fiu mbvtv fdbmq xpsspnpu ub 1 .NQ

Comments


  • 0
    scu10156165  commented on Jan. 30, 2024, 4:54 p.m.

    為甚麼上傳後 顯示compilation error


    • 0
      scu10156181  commented on Feb. 7, 2024, 2:59 p.m. edited

      result +=Character.toString((char)asc); asc強制轉型


      • 0
        scu10156165  commented on Feb. 7, 2024, 3:22 p.m.

        有了!謝謝


  • 0
    scu10156165  commented on Jan. 30, 2024, 4:52 p.m.

    import java.util.Scanner; public class p141 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        String x = input.nextLine();
        int n = input.nextInt();
        String result="";
        for(int i=0;i<x.length();i++) {
            int asc = x.charAt(i);
            if (asc<='Z'&&asc>='A') {
                asc = 'A'+(asc-'A'+n)%26;
            }
            else if(asc<='z'&&asc>='a') {
                asc = 'a'+(asc-'a'+n)%26;
            }
            result +=Character.toString(asc);
        }
        String rr [] = result.split(" ");
        for(int i=0;i<rr.length;i++) {
            for(int j=rr[i].length()-1;j>=0;j--) {
                System.out.print(rr[i].charAt(j));
            }
            System.out.print(" ");
        }
    }
    }