Posts [Java] 백준 #16310: 다이얼
Post
Cancel

[Java] 백준 #16310: 다이얼

문제

다이얼

전화를 걸고 싶은 번호가 있다면, 숫자를 하나를 누른 다음에 금속 핀이 있는 곳 까지 시계방향으로 돌려야 한다. 숫자를 하나 누르면 다이얼이 처음 위치로 돌아가고, 다음 숫자를 누르려면 다이얼을 처음 위치에서 다시 돌려야 한다.

숫자 1을 걸려면 총 2초가 필요하다. 1보다 큰 수를 거는데 걸리는 시간은 이보다 더 걸리며, 한 칸 옆에 있는 숫자를 걸기 위해선 1초씩 더 걸린다.

상근이의 할머니는 전화 번호를 각 숫자에 해당하는 문자로 외운다. 즉, 어떤 단어를 걸 때, 각 알파벳에 해당하는 숫자를 걸면 된다. 예를 들어, UNUCIC는 868242와 같다.

할머니가 외운 단어가 주어졌을 때, 이 전화를 걸기 위해서 필요한 시간을 구하는 프로그램을 작성하시오.

풀이

switch 문 이용

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
Scanner sc = new Scanner(System.in);
char[] arr = sc.next().toCharArray();
int result = 0;
for (int i = 0; i < str.length(); i++) {
  switch (arr[i]) {
    case 'A': case 'B': case 'C':
      result += 3;
      break;
    case 'D': case 'E': case 'F':
      result += 4;
      break;
    case 'G': case 'H': case 'I':
      result += 5;
      break;
    case 'J': case 'K': case 'L':
      result += 6;
      break;
    case 'M': case 'N': case 'O':
      result += 7;
      break;
    case 'P': case 'Q': case 'R': case 'S':
      result += 8;
      break;
    case 'T': case 'U': case 'V':
      result += 9;
      break;
    case 'W': case 'X': case 'Y': case 'Z':
      result += 10;
      break;
  }
}
System.out.println(result);

노가다…

if 문 이용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Scanner sc = new Scanner(System.in);
String str = sc.next().toCharArray();
int result = 0;
for (int i = 0; i < str.length(); i++) {
  if (arr[i] <= 'C') result += 3;
  else if (arr[i] <= 'F') result += 4;
  else if (arr[i] <= 'I') result += 5;
  else if (arr[i] <= 'L') result += 6;
  else if (arr[i] <= 'O') result += 7;
  else if (arr[i] <= 'S') result += 8;
  else if (arr[i] <= 'V') result += 9;
  else if (arr[i] <= 'Z') result += 10;
  }
sc.close();
System.out.println(result);

나눗셈 이용 + 예외 처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Scanner sc = new Scanner(System.in);

char[] arr = sc.next().toCharArray();
int result = 0;

for (char c : arr) {
  result += (c - 'A') / 3 + 3;
  if (c == 'S' || c == 'V' || c == 'Y' || c == 'Z') {
    result--;
  }
}

sc.close();
System.out.println(result);
This post is licensed under CC BY 4.0 by the author.

:coffee: [Java] LinkedList 구현하기

:book: 리팩토링 #1 (1): 메서드 분해와 기능 재분배

Loading comments from Disqus ...