题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner; /** * @author hll[yellowdradra@foxmail.com] * @since 2023-04-04 00:27 **/ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String plaintext = in.nextLine(); String ciphertext = in.nextLine(); System.out.println(encrypt(plaintext)); System.out.println(decrypt(ciphertext)); } public static String encrypt(String plaintext) { char[] chars = plaintext.toCharArray(); int d = 'a' - 'A'; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if ('0' <= c && c <= '8') { chars[i] = (char) (chars[i] + 1); } else if ('a' <= c && c <= 'y') { chars[i] = (char) (c - d + 1); } else if ('A' <= c && c <= 'Y') { chars[i] = (char) (c + d + 1); } else if (c == '9') { chars[i] = '0'; } else if (c == 'Z') { chars[i] = 'a'; } else if (c == 'z'){ chars[i] = 'A'; } } return String.valueOf(chars); } public static String decrypt(String ciphertext) { char[] chars = ciphertext.toCharArray(); int d = 'a' - 'A'; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if ('1' <= c && c <= '9') { chars[i] = (char) (chars[i] - 1); } else if ('b' <= c && c <= 'z') { chars[i] = (char) (c - d - 1); } else if ('B' <= c && c <= 'Z') { chars[i] = (char) (c + d - 1); } else if (c == '0') { chars[i] = '9'; } else if (c == 'A') { chars[i] = 'z'; } else if (c == 'a'){ chars[i] = 'Z'; } } return String.valueOf(chars); } }