String_암호_replace, parseInt, subString
✅ #*이 7개로 구성되어 있을 때, #는 1로, *은 0으로 반환하고 이진수를 십진수로 바꿔서 대문자 알파벳으로 출력해라
- 한 줄로 받은 String을 7개씩 s개의 String으로 나눈다.
- #은 1, *은 0으로 대체한다.
- 이진수를 십진수로 바꾼다.
- 십진수는 알파벳으로 캐스팅한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Main { public String solution(int s, String str){
String answer= "";
for(int i=0; i<s; i++){
String tmp= str.substring(0, 7).replace("#", "1").replace("*", "0");
int decimal= Integer.parseInt(tmp, 2);
answer += (char) decimal;
str = str.substring(7); //⭐️
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int s = sc.nextInt();
String str= sc.next();
System.out.println(T.solution(s, str));
}
}
//⭐️input:
//4
//#****###**#####**#####**##**
//⭐️output:
//COOL
🔵 ThingsILearned
✔️ 길이가 7*s인 String을 받았는데, 이걸 어떻게 7개씩 s개로 나누지?
이 부분이 제일 어려웠다. 새롭게 변수를 s번 선언해서 거기에디가 7개만큼 넣고..?
고민하다가 subString()
을 사용하였다.
subString()
을 사용하면 (0, 7)까지 자를 수 있는데,
반복문 안에서 (0,7)까지 자르기만 하면 앞에 부분만 계속 잘릴 것이다.
따라서 기존 String을 잘라낸 부분만큼 또 뒤에만 남기는 코드를 추가해 주어야 한다.
또는 subString()
으로 (i, i+7) 까지 자르고, for문을 7만큼씩 증가하도록 해도 된다.
⭐️ subString()
str.substring(0, 7)
을 하면 0에서부터 6까지 잘라서 반환한다.
따라서 그 나머지를 남기기 위해서는 str.substring(7)
라고 해서 7부터 잘라야 한다.
8부터 자르면 안됨❌
그리고 subString은 자르고 꼭 어딘가에 저장해 주어야 한다.
str.substring(7);
❌
str = str.substring(7);
⭕️
🟢 내가 짠 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Main { public String solution(int s, String str){
String answer= "";
str= str.replace("#", "1");
str= str.replace("*" , "0");
List<String> subStr= new ArrayList<>();
for(int i=0; i<str.length(); i+=7){
String substring = str.substring(i, i+7);
subStr.add(substring);
}
for(String x: subStr){
int decimal= Integer.parseInt(x, 2);
char c= (char) (decimal);
answer +=c;
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int s = sc.nextInt();
String str= sc.next();
System.out.println(T.solution(s, str));
}
}
This post is licensed under CC BY 4.0 by the author.