숫자 문자열과 영단어

2023. 1. 18. 21:25Programmers/Java

문제

 

결과 화면

 

1. if문으로 풀기

if문으로 해당 되는 문자열을 숫자로 바꿔주면 된다

다만 번거롭고 코드가 길어진다.

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
30
31
32
33
34
35
36
37
class Solution {
    public int solution(String s) {
             if (s.contains("zero")) {
                    s = s.replace("zero""0");
                }
                if (s.contains("one")) {
                    s =  s.replace("one""1");
                }
                if (s.contains("two")) {
                    s=s.replace("two""2");
                }
                if (s.contains("three")) {
                    s= s.replace("three""3");
                }
                if (s.contains("four")) {
                    s = s.replace("four""4");
                }
                if (s.contains("five")) {
                    s = s.replace("five""5");
                }
                if (s.contains("six")) {
                    s = s.replace("six""6");
                }
                if (s.contains("seven")) {
                    s = s.replace("seven""7");
                }
                if (s.contains("eight")) {
                    s = s.replace("eight""8");
                }
                if (s.contains("nine")) {
                    s = s.replace("nine""9");
                }
 
                return Integer.parseInt(s);
    }
}
 
cs

 

2. for문 돌리기

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int solution(String s) {
          String[] alphabet = {"zero""one""two""three""four""five""six""seven""eight""nine"};
 
       for(int i=0; i<10; i++){
           s = s.replace(alphabet[i], ""+i); 
       }
        return Integer.parseInt(s);
    }
}
 
cs

영어를 다 배열에 넣어두고 replace로 숫자로 바꿔주면 된다

다만, replace는 문자열에서 문자열로 바꿔주기 때문에 i에다가 ""를 더해준 것

문자열 + 숫자는 문자열로 취급하기 때문이다.

 

'Programmers > Java' 카테고리의 다른 글

두 개 뽑아서 더하기  (0) 2023.01.29
문자열 내 p와 y의 개수  (0) 2023.01.21
K번째수  (0) 2023.01.19
자릿수 더하기  (0) 2023.01.19
짝수와 홀수  (0) 2023.01.17