题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner;
// 深刻掌握字符与整型互转以及ASCII码表的记忆程度
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String source = in.nextLine();
String code = in.nextLine();
System.out.println(code(source, true));
System.out.println(code(code, false));
}
}
//加密 解密
public static String code(String source, boolean isEncode) {
char[] s = source.toCharArray();
for (int i = 0; i < source.length(); i++) s[i] = resolve(s[i], isEncode);
return new String(s);
}
//真正去解析每一个字符,处理转换
private static char resolve(char c, boolean isEncode) {
// 1 数字; 2 小写字母; 3 大写字母;
int off = isEncode ? 1 : -1;
char newc = '0';
if (48 <= c && c <= 57) {
newc = (char)((c + off + 10 - '0') % 10 + '0');
} else if (97 <= c && c <= 123) {
newc = (char)((c - 'a' + off + 26) % 26 + 'a' - 32);
} else if (65 <= c && c <= 90) {
newc = (char)((c - 'A' + off + 26) % 26 + 'a');
}
return newc;
}
}
