코딩테스트/[JAVA] 백준

[백준 | 1193번] 분수찾기

냠냠쿠 2023. 8. 13. 19:10
728x90
https://www.acmicpc.net/problem/1193

📝 나의풀이

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int N = scanner.nextInt(); //입력 받은 수
		
		int line = 0; //라인 수 
		int count = 0; //해당 라인 마지막 수를 구변할 변수
		int top=0; //분자
		int bottom = 0; //분모
		
		while (count<N) {
			line++;
			count = line * (line+1)/2;
		}
		
		if(line%2 !=0 ) {
			//홀수인경우 (분자 --, 분모++)
			top = 1+count-N;
			bottom = line+N-count;
		} else {
			//짝수인경우 (분자++ 분모--)
			bottom = 1+count-N;
			top = line+N-count;
		}
		System.out.println(top+"/"+bottom);
	}
}
  • 아래와 같은 방식으로 지그재그로 움직인다.
  • line이 짝수인경우(파랑) 분모가 증가, 분자가 감소 (3/1, 2/2, 1/3)
    line이 홀수인경우(빨강) 분모가 감소, 분자가 증가 (1/4, 2/3, 3/2, 4/1)
  • line은 line * (line+1)/2을 통해 구할 수 있다.
  • int line = 0; //라인 수 int count = 0; //해당 라인 마지막 수를 구변할 변수 int top=0; //분자 int bottom = 0; //분모 while (count<N) { line++; count = line * (line+1)/2; }
  • 라인을 구한 후 홀수인 경우 분모가 증가 top = 1+count-N;하고 분자가 감소 bottom = line+N-count; 하도록, 짝수인 경우 이와 반대로 설정 해 주면 된다.
728x90