题解 | #字符串加解密#

字符串加解密

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;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 15:46
已编辑
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务