题解 | #字符串加解密#

字符串加解密

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);
    }

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-24 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务