ZZULIOJ 1164: String Encryption, Java

ZZULIOJ 1164: String Encryption, Java

Question description

Input a string of characters (length not exceeding 100) and a positive integer k, encrypt the English letters in it and output the encrypted string, leaving non-English letters unchanged. Encryption idea: Add an ordinal k to each letter c, that is, replace it with the k-th letter following it. The transformation formula is: c=c+k. If the letter is z, the next letter is a, that is, the alphabetic characters form a circle.

enter

The first line of input is a number of characters, ending with a carriage return. The second line of input is an integer k, where k is a positive integer in the range of int;

output

Output the encrypted string.

Sample inputCopy
12kjsdZjk
280
Sample outputCopy
12edmxTde
hint

Note that even if k is controlled within a range less than 26 through modulo operation, the problem of char type overflow still needs to be considered. For example, 'z' + 10 will exceed the representation range of char. But fortunately, we only need to consider the overflow of the char type when storing in memory, and there will be no overflow during the calculation process, because the char will be promoted to the int type during the calculation process.

import java.io.*;

public class Main {
    
    
    public static void main(String[] args) throws IOException {
    
    
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        char[] a = bf.readLine().toCharArray();
        int k = Integer.parseInt(bf.readLine());
        for (int i = 0; i < a.length; i++) {
    
    
            if (a[i] >= 'a' && a[i] <= 'z') {
    
    
                a[i] = (char) ((a[i] - 'a' + k) % 26 + 'a');
            }
            if (a[i] >= 'A' && a[i] <= 'Z') {
    
    
                a[i] = (char) ((a[i] - 'A' + k) % 26 + 'A');
            }
        }
        bw.write(a);
        bw.close();
    }
}

Guess you like

Origin blog.csdn.net/qq_52792570/article/details/132641634