잡다한 배똥월드

728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

1292번: 쉽게 푸는 문제

첫째 줄에 구간의 시작과 끝을 나타내는 정수 A, B(1 ≤ A ≤ B ≤ 1,000)가 주어진다. 즉, 수열에서 A번째 숫자부터 B번째 숫자까지 합을 구하면 된다.

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 a = Integer.parseInt(s[0]);
		int b = Integer.parseInt(s[1]);
		
		int result = 0;
		
		int position = 1;
		int number = 1;
		for (int i = 1; i <= b; i++) {
			if (position < i) {
				number++;
				position += number;
			}
			if (i >= a && i <= b) result += number;
		}
		
		System.out.println(result);
	}
}

 

문제 결과 메모리 시간 코드 길이
1292 맞았습니다!! 14160 KB 124 ms 528 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

9372번: 상근이의 여행

첫 번째 줄에는 테스트 케이스의 수 T(T ≤ 100)가 주어지고, 각 테스트 케이스마다 다음과 같은 정보가 주어진다. 첫 번째 줄에는 국가의 수 N(2 ≤ N ≤ 1 000)과 비행기의 종류 M(1 ≤ M ≤ 10 000) 가

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));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        //테스트케이스 갯수
		int t = Integer.parseInt(br.readLine());
		
        //테스트케이스만큼 반복
		for (int T = 0; T < t; T++) {
			String[] nm = br.readLine().split(" ");
            
			int n = Integer.parseInt(nm[0]); //국가 수
			int m = Integer.parseInt(nm[1]); //비행기 종류
			
            //m만큼 읽어들이고 끝내기
			for (int i = 0; i < m; i++) {
				br.readLine();
			}
			
            //결론은 n-1임
			bw.write(n-1 + "\n");
		}		
		bw.flush();
		bw.close();
	}
}

 

문제 결과 메모리 시간 코드 길이
9372 맞았습니다!! 24216 236 573

 

 

 

 

 

 

728x90
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
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

1094번: 막대기

지민이는 길이가 64cm인 막대를 가지고 있다. 어느 날, 그는 길이가 Xcm인 막대가 가지고 싶어졌다. 지민이는 원래 가지고 있던 막대를 더 작은 막대로 자른다음에, 풀로 붙여서 길이가 Xcm인 막대

www.acmicpc.net

 

 

 

 

 

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));
		
		//만들어야 할 길이
		int X = Integer.parseInt(br.readLine());
	
		//첫 막대기 길이
		int stick = 64;

		//남아있는 막대기 길이
		ArrayList<Integer> all = new ArrayList<>();
		//all 안에 들어있는 막대기 모든 길이
		int allStick = 0;
		
		//while문으로 막대 길이와 남아있는 막대 길이가 X보다 작거나 같아질 때까지 반복
		while (stick + allStick > X) {
			//막대기를 절반으로 자르고
			stick /= 2;
			//절반으로 잘린 막대 길이와 남아있는 막대기 모든 길이의 합이 X보다 작으면
			if (stick + allStick < X) {
				//다른 절반으로 잘린 막대기는 보관
				all.add(stick);
				allStick += stick;
			}
		}
		//stick은 따로 추가해줘야하기 때문에 +1을 해줌
		System.out.println(all.size()+1);
	}
}

 

문제 결과 메모리 시간 코드 길이
1094 맞았습니다!! 14328 KB 128 ms 503 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

4344번: 평균은 넘겠지

대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.

www.acmicpc.net

 

 

 

 

 

▽ Stream으로 계산하는 코드 ▽ 

import java.io.*;
import java.util.Arrays;
public class Main {	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
		
		for (int t = 0; t < n; t++) {
			//Stream을 이용하여 String[]을 int[]로 변환하는 방법
			int[] list = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
			
			int num = list[0];
			int[] score = Arrays.copyOfRange(list, 1, list.length);
			
			//Stream을 이용하여 int배열 내 숫자의 총 합을 내는 방법
			double avg = Arrays.stream(score).sum() / num;

			//Stream을 이용하여 int배열 내 숫자들 중 조건에 맞는 숫자들 개수 구하는 방법
			double count = Arrays.stream(score).filter(number -> number > avg).count();

			bw.write(String.format("%.3f", count / num * 100) + "%\n");
		}
		bw.flush();
		bw.close();
	}
}

 

▽ for문으로 계산하는 코드 

import java.io.*;
public class Main {	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
		
		for (int t = 0; t < n; t++) {
			String[] temp = br.readLine().split(" ");

			int num = Integer.parseInt(temp[0]);
			int[] score = new int[num];
			
			int sum = 0;
			for (int i = 1; i < temp.length; i++) {
				score[i-1] = Integer.parseInt(temp[i]);
				sum += score[i-1];
			}
			
			double avg = sum / num;
			int count = 0;
			for (int i = 0; i < score.length; i++) {
				if (score[i] > avg) count++;
			}
			
			bw.write(String.format("%.3f", (double) count / num * 100) + "%\n");
		}
		bw.flush();
		bw.close();
	}
}

 

코드 문제 결과 메모리 시간 코드 길이
for문 4344 맞았습니다!! 15880 176 829
Stream 4344 맞았습니다!! 16296 192 836

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

1236번: 성 지키기

첫째 줄에 성의 세로 크기 N과 가로 크기 M이 주어진다. N과 M은 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 성의 상태가 주어진다. 성의 상태는 .은 빈칸, X는 경비원이 있는 칸이다

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[] rc = br.readLine().split(" ");
		int r = Integer.parseInt(rc[0]);
		int c = Integer.parseInt(rc[1]);
		
        	//그 다음 줄 부터는 성의 상태
		String[][] map = new String[r][c];
		
        	//출력을 위해 체크용.
       		//행에 배치해야할 경비 수와 열에 배치해야할 경비 수
		int rCount = 0;
		int cCount = 0;
        
       		//열은 바로바로 체크가 안되니까 한 줄씩 비어있는지 아닌지를 파악하기 위해 boolean 배열
		boolean[] cCheck = new boolean[c];
		
        	//한 줄 씩 입력 받으면서 해당 행에 경비가 있는지 => 없으면 rCount +1 
		//해당 열에 경비가 있으면 cCheck 상태 바꾸기
		for (int i = 0; i < r; i++) {
			map[i] = br.readLine().split("");
			boolean value = false;
			for (int j = 0; j < c; j++) {
				if (map[i][j].equals("X")) {
					if (!value) value = true;
					if (!cCheck[j]) cCheck[j] = true;
				}
			}
			if (!value) rCount++;
		}
		
        	//cCheck를 돌면서 빈 경비 개수 세기
		for (int i = 0; i < c; i++) {
			if (!cCheck[i]) cCount++;
		}
        
       		//rCount와 cCount 중 큰 숫자 리턴
		System.out.println(Math.max(rCount, cCount));
	}
}

 

문제 결과 메모리 시간 코드 길이
1236 맞았습니다!! 14652 KB 140 ms 797 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

1032번: 명령 프롬프트

첫째 줄에 파일 이름의 개수 N이 주어진다. 둘째 줄부터 N개의 줄에는 파일 이름이 주어진다. N은 50보다 작거나 같은 자연수이고 파일 이름의 길이는 모두 같고 길이는 최대 50이다. 파일이름은

www.acmicpc.net

 

 

 

 

 

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));
		
        //가져올 단어 개수
		int n = Integer.parseInt(br.readLine());
		
        //단어를 String배열로 변환하여 담을 arraylist
        ArrayList<String[]> arr = new ArrayList<>();
		
        //arr에 담기
		for (int i = 0; i < n; i++) {
			arr.add(br.readLine().split(""));
		}
		
        //리턴할 문자열 배열
		String[] result = Arrays.copyOf(arr.get(0), arr.get(0).length);
		
    	앞에서부터 비교해서 만약 문자가 다르면 ?로 변환
		for (int i = 0; i < n; i++) {
			String[] a = arr.get(i);
			for (int j = i+1; j < n; j++) {
				String[] b = arr.get(j);
				for (int k = 0; k < a.length; k++) {
					if (!a[k].equals(b[k]) && !result[k].equals("?")) {
						result[k] = "?";
					}
				}
			}
		}
        
        //String.join함수로 묶은 후 리턴
		System.out.println(String.join("", result));	
	}
}

 

문제 결과 메모리 시간 코드 길이
1032 맞았습니다!! 15380KB 156ms 755B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

 

 

import java.util.*;
class Solution {
    public int solution(String begin, String target, String[] words) {
    
    	//words에 target이 있는지 없는지 확인
        boolean value = false;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(target)) {
                value = true;
                break;
            }
        }
        if (!value) return 0;
        
        //words의 단어들을 비교하기 편하게 char배열로 변환 후 ArrayList에 넣기
        ArrayList<char[]> list = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            list.add(words[i].toCharArray());
        }
        
        //target도 한번씩 확인을 해야하기 때문에 미리 char배열로 만들어놓기
        char[] base = target.toCharArray();
        
       	//너비우선탐색인 BFS로 탐색하기 위해서 Queue 선언
        Queue<word> q = new LinkedList<>();
        
        //큐에 begin을 char배열로 변환하여 word 객체로 만들어서 넣기
        q.add(new word(0, begin.toCharArray()));
        
        //q가 비워질 때까지 반복
        while (!q.isEmpty()) {
        	//큐의 제일 상단 값 가져오기
            word w = q.poll();
            char[] temp = w.list;
            int index = w.index;
            
            //temp와 target이 같은지 안같은지 비교. 같으면 해당 index 리턴
            if (check(base, temp) == 0) return index;

			//temp와 list에 있는 단어들 비교
            for (int i = 0; i < list.size(); i++) {
                char[] data = list.get(i);
                //글자가 하나만 다르면 list에서 지우면서 q에 넣기
                if (check(temp, data) == 1) q.add(new word(index+1, list.remove(i)));
            }
        }
        return 0;
    }
    
    //a 글자와 b 글자가 몇 글자 다른지 비교하는 함수
    public int check(char[] a, char[] b) {
        int count = a.length;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == b[i]) count--;
        }
        
        return count;
    }
}

class word {
    int index;
    char[] list;
    public word (int i, char[] list) {
        this.index = i;
        this.list = Arrays.copyOf(list, list.length);
    }
}

 

테스트 1 통과 (0.50ms, 83.1MB)
테스트 2 통과 (0.40ms, 81.9MB)
테스트 3 통과 (0.53ms, 69.9MB)
테스트 4 통과 (0.39ms, 74.8MB)
테스트 5 통과 (0.02ms, 75MB)

 

 

 

 

 

 

728x90

+ Recent posts