题解 | #字符串加解密# 根据题意简单模拟

字符串加解密

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

import java.util.Scanner;

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
         String encip = in.nextLine();
         String decryption = in.nextLine();
         System.out.println(encipher(encip));
         System.out.println(decryption(decryption));
    }

    private static String encipher(String str){
        StringBuilder sb = new StringBuilder();
        char[] chars = str.toCharArray();
        for(char c: chars){
            if(Character.isDigit(c)){
             char temp = (char)('0'+(c-'0'+1)%10);
             sb.append(temp);
            }else if(Character.isUpperCase(c)){
              char temp = (char)('a'+(c-'A'+1)%26);
              sb.append(temp);
            }else if(Character.isLowerCase(c)){
               char temp = (char)('A'+(c-'a'+1)%26);
              sb.append(temp); 
            }
        }
        return sb.toString();
    }


    private static String decryption(String str){
        StringBuilder sb = new StringBuilder();
        char[] chars = str.toCharArray();
        for(char c:chars){
             if(Character.isDigit(c)){
             char temp = (char)('0'+(c-'0'-1+10)%10);
             sb.append(temp);
            }else if(Character.isUpperCase(c)){
              char temp = (char)('a'+(c-'A'-1+26)%26);
              sb.append(temp);
            }else if(Character.isLowerCase(c)){
               char temp = (char)('A'+(c-'a'-1+26)%26);
              sb.append(temp); 
            }
        }
        return sb.toString();
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务