题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.nextLine(); String s2 = in.nextLine(); System.out.println(encrypt(s1)); System.out.println(decrypt(s2)); } private static String encrypt(String s) { StringBuilder sb = new StringBuilder(); char res = ' '; for (char ch : s.toCharArray()) { if ('a' <= ch && ch < 'z') { res = (char)(ch + 'A' - 'a' + 1); sb.append(res); } else if (ch == 'z') { sb.append('A'); } else if ('A' <= ch && ch < 'Z') { res = (char)(ch + 'a' - 'A' + 1); sb.append(res); } else if (ch == 'Z') { sb.append('a'); } else { int num = ch - '0'; num = (num + 1) % 10; sb.append(num); } } return sb.toString(); } private static String decrypt(String s) { StringBuilder sb = new StringBuilder(); char res = ' '; for (char ch : s.toCharArray()) { if ('a' < ch && ch <= 'z') { res = (char)(ch + 'A' - 'a' - 1); sb.append(res); } else if (ch == 'a') { sb.append('Z'); } else if ('A' < ch && ch <= 'Z') { res = (char)(ch + 'a' - 'A' - 1); sb.append(res); } else if (ch == 'A') { sb.append('z'); } else { int num = ch - '0'; if (num == 0) { num = 9; } else { num = num - 1; } sb.append(num); } } return sb.toString(); } }