题解 | #字符串加解密#
字符串加解密
http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String a = in.next();
String b = in.next();
System.out.println(encrypt(a));
System.out.println(decode(b));
}
}
//加密方法
private static String encrypt(String str) {
char[] cs = str.toCharArray();
StringBuilder strB = new StringBuilder(cs.length);
for (char c : cs) {
strB.append(encryptChar(c));
}
return strB.toString();
}
//解密方法
private static String decode(String str) {
char[] cs = str.toCharArray();
StringBuilder strB = new StringBuilder(cs.length);
for (char c : cs) {
strB.append(decodeChar(c));
}
return strB.toString();
}
private static char encryptChar(char c) {
char result = c;
int l = (int) 'A' - (int) 'a';
//数字加密
if(c >= '0' && c < '9') {
result = (char)((int)c + 1);
} else if (c == '9') {
result = '0';
}
//字母加密
if(c >= 'a' && c < 'z') { //小写字母
result = (char)( (int)c + 1 + l );
} else if (c >= 'A' && c < 'Z') { //大写字母
result = (char)( (int)c + 1 - l );
} else if ( c == 'z') {
result = 'A';
} else if ( c == 'Z') {
result = 'a';
}
return result;
}
private static char decodeChar(char c) {
char result = c;
int l = (int) 'A' - (int) 'a';
//数字解密
if(c > '0' && c <= '9') {
result = (char)((int)c - 1);
} else if (c == '0') {
result = '9';
}
//字母解密
if(c > 'a' && c <= 'z') { //小写字母
result = (char)( (int)c - 1 + l );
} else if (c > 'A' && c <= 'Z') { //大写字母
result = (char)( (int)c - 1 - l );
} else if ( c == 'a') {
result = 'Z';
} else if ( c == 'A') {
result = 'z';
}
return result;
}
}