看板 java 關於我們 聯絡資訊
public static void main(String[] args) { Compress c = new Compress(); System.out.println(c.compressProcess("3", "MEET ME XYZ")); } public String compressProcess(String A, String B) { int a = Integer.parseInt(A); StringBuffer sb = new StringBuffer(); for(int i = 0; i < B.length(); i++) { char b = B.charAt(i); if(b >= 65 && b <= 90 && a >= 0) sb.append((char) (65 + (((b - 65) + a) % 26))); else sb.append(b); } return sb.toString(); } 結果: PHHW PH ABC ※ 引述《hbk1015 (邪道)》之銘言: : 各位好,今年台銀招考IT人員的試題我的寫法不知道還有沒有改良的空間,請大家賜教, : 原始程式如下: : import java.io.*; : public class Compress{ : private String S ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; : private String C = ""; : public static void main(String[] args){ : Console CC = System.console(); : String A = CC.readLine(); : String B = CC.readLine(); : Compress CP = new Compress(); : String C = CP.compressProcess(A, B); : System.out.println(C); : } : public String compressProcess(String A, String B){ : int a = Integer.parseInt(A); : int b = 0; : for(int i = 0; i < B.length(); i++){ : for(int j = 0; j < S.length(); j++){ : if(S.charAt(j) == B.charAt(i)){ : b = (j + a) % 26; : C += S.charAt(b); : } : } : } : return C; : } : } : 題目請參考http://210.68.8.81/tw/ptc_99taiwan/doc/rinbancnw.pdf -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.70.79.93
mgtsai:那個 else sb.append(b); 去掉, 因為找不到時不會加進 C 中 11/19 00:14
bleed1979:測資應該只限定A ~ Z和空白字元,仍要加入。 只是, 11/19 07:46
bleed1979:如果是OJ的題目,我就建表輸出了。 11/19 07:48
bleed1979:另外,給原po,a >= 0這個我會一開始就判斷。 11/19 07:50
csieflyman:我隨手寫的沒想這麼多例外檢查啦 重點是使用ASCII code 11/19 09:57
csieflyman:因為原po是問有沒有改良的方法 11/19 09:59
derekQQ:綜合上下文,我比較喜歡這個寫法~ 11/21 17:13
derekQQ:直接對ASCII 做處理就好 11/21 17:14