코딩테스트/백준

[Java] 백준 - 11203번 : Numbers On a Tree (Silver V)

배똥회장 2022. 8. 9. 13:30
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

11203번: Numbers On a Tree

The only line of input contains the height of the tree H, 1 ≤ H ≤ 30 and a string consisting of the letters ‘L’ and ‘R’, denoting a path in the tree starting in the root. The letter ‘L’ denotes choosing the left child, and the letter ‘R

www.acmicpc.net

 

 

 

 

 

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().split(" ");
        
        //트리의 높이
		int n = Integer.parseInt(s[0]);
		
        //트리의 높이로 최정점 노드의 번호를 가져올 수 있음
        //이 때, int로 선언할 경우 높이 범위인 30을 계산할 때 int 범위를 초과하여 오류 발생함
		long num = (long) Math.pow(2, n+1) - 1;
		
        //최상위 노드의 위치
		int index = 1;
		
        //s의 길이가 1인 경우에는 루트가 없다는 뜻으로 그냥 리턴해야함
		if (s.length > 1) {
        	//글자 비교가 편하게 char[] 변환
			char[] word = s[1].toCharArray();
            
            //word 방문용 for문
			for (int i = 0; i < word.length; i++) {
				//만약 L이면 현재 위치에서 2만 곱하고, R일 경우에는 2를 곱하고 1을 더해줘야함 
                index = word[i] == 'L' ? index * 2 : index * 2 + 1;
			}
		}
	
    	//리턴할 숫자는 최상위 노드 숫자에서 위치를 빼고 1을 더해주면 됨
		System.out.println(num - index + 1);
	}
}

 

문제 결과 메모리 시간 코드 길이
11203 맞았습니다!! 14308 KB 128 ms 529 B

 

 

 

 

 

 

728x90