[BaekJoon] #5622 - 다이얼 [Java][C++][Python]
[BaekJoon] #5622 - 다이얼 [Java][C++][Python]
1. 아이디어
단어의 알파벳에 해당하는 숫자를 차례로 걸 때 걸리는 시간의 합을 구하는 문제다. 숫자 1을 거는 데 2초가 걸리고 한 칸 옆의 숫자로 갈 때마다 1초씩 늘어나므로, 1부터 9까지의 숫자 $d$를 거는 시간은 $d + 1$초다. 다만 알파벳은 숫자 2부터 9까지에 3개씩 배정되는데 7과 9만 4개라, 알파벳 순번을 3으로 나누는 것만으로는 숫자를 구할 수 없다. 그래서 26개 알파벳마다 거는 데 걸리는 시간을 표로 만들어 두고 글자마다 찾아 더한다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int[] arr = {3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10};
int sum = 0;
for (char c : s.toCharArray()) {
sum += arr[c - 'A'];
}
System.out.println(sum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <bits/stdc++.h>
using namespace std;
int arr[26] = {3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
int sum = 0;
for (char c : s) {
sum += arr[c - 'A'];
}
cout << sum;
}
1
2
3
4
5
6
import sys
input = sys.stdin.readline
arr = [3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10]
print(sum(arr[ord(c) - ord("A")] for c in input().rstrip()))
문자열끼리는 뺄 수 없어 ord로 코드값을 구한 뒤 빼서 인덱스를 만들었다.
This post is licensed under CC BY 4.0 by the author.