티스토리 뷰

알고리즘

<SWEA> 8556-북북서

koyuchang 2020. 8. 19. 14:40

<풀이>

west일때와 north일때와 다른 연산을 해주어야 하고, 연산에서 소숫점이 발생하면(실수) 나중에 소수점이 사라질때 까지 X2를 해주는것이 핵심이다.

Ex) 'northnorthwest'일 경우,

1. west: west는 90도 이므로 ans에 90이 들어간다.(ans=90)

2. northwest:  그 다음 단어는 north이므로 90/2^1를 빼준다.(ans=45)

3. northnorthwest: 그 다음 단어는 north 이므로 90/2^2를 빼준다.(ans=22.5)

 

여기까지 연산을 끝낸 후 ans를 살펴보면 소숫점이 있는 실수라는 것을 알 수 있다. 이제 ans가 정수가 될때까지 X2를 해준다. 그리고 X2를 해준만큼 k변수에도 X2를 해준다.

ans는 45가 되고 한번 X2를 해주었으므로 k=2가 된다. 그래서 결과값은 45/2라는 것을 알 수 있다.

package algorithm;
import java.util.Scanner;
import java.util.Stack;
public class S8556_북북서 {
static double ans;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T;
T = sc.nextInt();
for (int test_case = 1; test_case <= T; test_case++) {
ans = 0;
Stack<Character> st = new Stack();
String str = sc.next();
if (str.contains("north")) {
str = str.replaceAll("north", "*");
}
if (str.contains("west")) {
str = str.replaceAll("west", "-");
}
for (int i = 0; i < str.length(); i++) {
st.add(str.charAt(i));
}
int j = 0;// 제곱 계산에 사용
double tp = 0;// 현재 값에 더할(뺄)값
int k = 1;// 나중에 정답에 붙일 /k 형의 값
while (!st.isEmpty()) {// 스택에서 하나씩 꺼내면서 계산
char tmp = st.pop();
if (j == 0) {// 초기값 설정
if (tmp == '*') {
ans = 0;
} else {
ans = 90;
}
} else {
tp = 90 / Math.pow(2, j);
if (tmp == '*') {// north일경우
ans -= tp;// 현재 값에서 빼준다.
} else {// west일경우
ans += tp;// 현재 값에서 더해준다.
}
}
j++;
}
boolean flag = true;
while (flag) {
if (ans == (int) ans) {// 정수형이랑 실수형태랑 다르면 계속 진행
flag = false;
} else {
ans *= 2;// 2씩 계속 곱해준다.
k *= 2;
}
}
if (k != 1) {// 결과값이 정수형태가 아니였으면
System.out.printf("#%d %s\n", test_case, (int) ans + "/" + k);
} else {// 결과값이 실수형태가 아니였으면
System.out.printf("#%d %d\n", test_case, (int) ans);
}
}
}
}
view raw 북북서 hosted with ❤ by GitHub

'알고리즘' 카테고리의 다른 글

<baekjoon> 단어 수학  (0) 2020.08.22
<baekjoon> 별자리 만들기  (0) 2020.08.21
<baekjoon> 2583- 영역 구하기  (0) 2020.08.17
<SWEA> 1238-Contact  (0) 2020.08.17
<HackerRank> Grading Students  (0) 2020.05.21
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함