7题解 | #字符串加解密#

字符串加解密

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);
        // 注意 hasNext 和 hasNextLine 的区别
        String plaintext = in.nextLine();
        String ciphertext = in.nextLine();

        String cipher = encrypt(plaintext);
        String plain = decrypt(ciphertext);

        
        System.out.println(cipher);
        System.out.println(plain);
        
    }

    public static String encrypt(String plaintext){
        StringBuilder sb = new StringBuilder();
        char [] ch = plaintext.toCharArray();
        for(int i = 0;i<plaintext.length();i++){
            if(Character.isLowerCase(ch[i]) && ch[i]!='z'){
                sb.append((char)(ch[i] - 32 + 1));
                continue;
            }
            if(Character.isUpperCase(ch[i]) && ch[i]!='Z'){
                sb.append((char)(ch[i] + 32 + 1));
                continue;
            }
            if(ch[i]=='z'){
                sb.append('A');
                continue;
            }
            if(ch[i]=='Z'){
                sb.append('a');
                continue;
            }
            if(ch[i]>='0' && ch[i]<='8'){
                sb.append(Integer.valueOf(ch[i]+"") + 1);
                continue;
            }
            if(ch[i]=='9'){
                sb.append(0);
                continue;
            }
            sb.append(ch[i]);
        }
        
return sb.toString();
    }
    public static String decrypt(String ciphertext){
        StringBuilder sb = new StringBuilder();
        char [] ch = ciphertext.toCharArray();
        for(int i = 0;i<ciphertext.length();i++){
            if(Character.isLowerCase(ch[i]) && ch[i]!='a'){
                sb.append((char)(ch[i] - 32 - 1));
                continue;
            }
            if(Character.isUpperCase(ch[i]) && ch[i]!='A'){
                sb.append((char)(ch[i] + 32 - 1));
                continue;
            }

            if(ch[i]=='a'){
                sb.append('Z');
                continue;
            }
            if(ch[i]=='A'){
                sb.append('z');
                continue;
            }

            if(ch[i]>='1' && ch[i]<='9'){
                sb.append(Integer.valueOf(ch[i]+"") - 1);
                continue;
            }
            
            if(ch[i]=='0'){
                sb.append(9);
                continue;
            }
            sb.append(ch[i]);
        }
        
        return sb.toString();
    }
}

全部评论

相关推荐

没有offer的小土豆:专业面试一般是分配面试官然后联系你面试 应该是还没给你分配对应面试官
点赞 评论 收藏
分享
11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务