题解 | #字符串加解密#
字符串加解密
http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
1.难点是在处理数字加密和解密的时候容易出错
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = 0; while(sc.hasNextLine()) { String str = sc.nextLine(); i++; if (i % 2 == 0) { decrypt(str); } else { encrypt(str); } } } // 加密 public static void encrypt(String str) { StringBuilder stringBuilder = new StringBuilder(); char[] charArray = str.toCharArray(); for (char ch : charArray) { // 判断是否为字母 if(Character.isLetter(ch)) { // 如果字母为大写 if (ch >= 65 && ch <= 90) { if (ch == 'Z') { stringBuilder.append("a"); } else { stringBuilder.append((char)(ch+33)); //stringBuilder.append((String.valueOf((char)(ch + 1)).toLowerCase())); } // 如果字母为小写 } else if (ch >= 97 && ch <= 122){ if (ch == 'z') { stringBuilder.append("A"); } else { stringBuilder.append((char)(ch-31)); //stringBuilder.append((String.valueOf((char)(ch + 1)).toUpperCase())); } } // 为数字 } else if (Character.isDigit(ch)) { if (ch == '9') { stringBuilder.append("0"); } else { //stringBuilder.append((ch+1)); stringBuilder.append(Integer.parseInt(String.valueOf(ch)) + 1); } } } System.out.println(stringBuilder); } // 解密 public static void decrypt(String str) { StringBuilder stringBuilder = new StringBuilder(); char[] charArray = str.toCharArray(); for (char ch : charArray) { // 如果字母为小写 if (ch >= 97 && ch <= 122) { if (ch == 'a') { stringBuilder.append("Z"); } else { stringBuilder.append((char)(ch-33)); //stringBuilder.append((String.valueOf((char)(ch - 1)).toUpperCase())); } // 如果字母为大写 } else if (ch >= 65 && ch <= 90){ if (ch == 'A') { stringBuilder.append("z"); } else { stringBuilder.append((char)(ch+31)); //stringBuilder.append((String.valueOf((char)(ch - 1)).toLowerCase())); } } else if (Character.isDigit(ch)) { if (ch == '0') { stringBuilder.append("9"); } else { //stringBuilder.append((ch-1)+""); stringBuilder.append(Integer.parseInt(String.valueOf(ch)) - 1); } } } System.out.println(stringBuilder); } }