题解 | #字符串加解密#

字符串加解密

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        String s2 = in.nextLine();
        System.out.println(encrypt(s1));
        System.out.println(decrypt(s2));
    }

    private static String encrypt(String s) {
        StringBuilder sb = new StringBuilder();
        char res = ' ';
        for (char ch : s.toCharArray()) {
            if ('a' <= ch && ch < 'z') {
                res = (char)(ch + 'A' - 'a' + 1);
                sb.append(res);
            } else if (ch == 'z') {
                sb.append('A');
            } else if ('A' <= ch && ch < 'Z') {
                res = (char)(ch + 'a' - 'A' + 1);
                sb.append(res);
            } else if (ch == 'Z') {
                sb.append('a');
            } else {
                int num = ch - '0';
                num = (num + 1) % 10;
                sb.append(num);
            }

        }
        return sb.toString();
    }

    private static String decrypt(String s) {
        StringBuilder sb = new StringBuilder();
        char res = ' ';
        for (char ch : s.toCharArray()) {
            if ('a' < ch && ch <= 'z') {
                res = (char)(ch + 'A' - 'a' - 1);
                sb.append(res);
            } else if (ch == 'a') {
                sb.append('Z');
            } else if ('A' < ch && ch <= 'Z') {
                res = (char)(ch + 'a' - 'A' - 1);
                sb.append(res);
            } else if (ch == 'A') {
                sb.append('z');
            } else {
                int num = ch - '0';
                if (num == 0) {
                    num = 9;
                } else {
                    num = num - 1;
                }
                sb.append(num);
            }

        }
        return sb.toString();
    }
}

全部评论

相关推荐

双非坐过牢:非佬,可以啊10.28笔试,11.06评估11.11,11.12两面,11.19oc➕offer
点赞 评论 收藏
分享
头像
11-09 12:17
清华大学 C++
out11Man:小丑罢了,不用理会
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务