[BaekJoon] 2920번 - 음계 [Java][C++]
[BaekJoon] 2920번 - 음계 [Java][C++]
1. 문제 풀이
오름차순인지 내림차순인지를 판단하는 불 타입 변수를 활용했다. 현재 음이 이전 음보다 큰지 작은지로 해당 변수를 갱신해줘서 최종적으로 ascending인지, descending인지, 아니면 mixed인지 판별했다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int[] arr = new int[8];
for (int i = 0; i < 8; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
boolean isAsc = true;
boolean isDesc = true;
for (int i = 1; i < 8; i++) {
if (arr[i] < arr[i - 1]) {
isAsc = false;
}
if (arr[i] > arr[i - 1]) {
isDesc = false;
}
}
if (isAsc) {
System.out.println("ascending");
} else if (isDesc) {
System.out.println("descending");
} else {
System.out.println("mixed");
}
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> v(8);
for (int& x : v) cin >> x;
bool isAsc = true;
bool isDesc = true;
for (int i = 1; i < 8; i++) {
if (v[i] < v[i - 1]) {
isAsc = false;
}
if (v[i] > v[i - 1]) {
isDesc = false;
}
}
if (isAsc) {
cout << "ascending";
} else if (isDesc) {
cout << "descending";
} else {
cout << "mixed";
}
}
This post is licensed under CC BY 4.0 by the author.