题解 | #简单密码#
简单密码
http://www.nowcoder.com/practice/7960b5038a2142a18e27e4c733855dac
核心思想可以分为以下几步:
- 定义一个字符存储StringBuilder ans = new StringBuilder();
- 如果是大写字母,将其转化为小写,转化为ASCII码加1(即字母右移),然后再将ASCII码转化为对应的字母;
- 如果是'Z',则直接向ans中加入'a';
- 如果小写,找到对应ASCII码范围内的添加值,加入ans中即可
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
SimpleCode(str);
}
}
public static void SimpleCode(String str){
StringBuilder ans = new StringBuilder();
//将字符串转存到char组中
char[] s = str.toCharArray();
//遍历字符串
for(int i = 0; i < s.length; i++){
//判断是否为大写字母,将其转化为小写
//转化为ASCII码加1(即字母右移),然后再将ASCII码转化为对应的字母
//如果是'z',则直接向ans中加入'a'
if(Character.isUpperCase(s[i])){
s[i] = Character.toLowerCase(s[i]);
if (s[i] == 'z'){
ans.append('a');
}else{
char res = (char) (s[i] + 1);
ans.append(res);
}
//判断是否为小写,找到对应ASCII码范围内的添加值,加入ans中即可
}else if (Character.isLowerCase(s[i])){
int digital = s[i] - 'a';
if (0 <= digital && digital <= 2){
ans.append(2);
}else if (3 <= digital && digital <= 5){
ans.append(3);
}else if (6 <= digital && digital <= 8){
ans.append(4);
}else if (9 <= digital && digital <= 11){
ans.append(5);
}else if (12 <= digital && digital <= 14){
ans.append(6);
}else if (15 <= digital && digital <= 18){
ans.append(7);
}else if (19 <= digital && digital <= 21){
ans.append(8);
}else if (22 <= digital && digital <= 25){
ans.append(9);
}
}else{
ans.append(s[i]);
}
}
System.out.println(ans.toString());
}
}