컴공댕이 공부일지

[c언어, java] 백준 (2675 문자열 반복 / 1002 터렛) 본문

문제 풀이/코딩 문제 풀이 모음

[c언어, java] 백준 (2675 문자열 반복 / 1002 터렛)

은솜솜솜 2023. 3. 21. 18:55
728x90

1. 2675 문자열 반복 [ c언어, java ]

브론즈 2

같은 문제를 두 언어로 풀어보았다. 문자열을 다루기엔 각종 메서드가 다양한 자바가 편한 것 같다.

 

https://www.acmicpc.net/problem/2675

 

2675번: 문자열 반복

문자열 S를 입력받은 후에, 각 문자를 R번 반복해 새 문자열 P를 만든 후 출력하는 프로그램을 작성하시오. 즉, 첫 번째 문자를 R번 반복하고, 두 번째 문자를 R번 반복하는 식으로 P를 만들면 된다

www.acmicpc.net

 

c언어 코드

string.h 헤어파일에 내장된 strlen을 써서 문자열 총 길이 구함.

#include <stdio.h>
#include <string.h>

int main()
{
    int t=0;
    scanf("%d", &t); 
    
    while(t!=0) {

        int r=0;
        scanf("%d", &r);
        char str[20]; //20
        scanf("%s",str);
        
        int i=0;
        int l=strlen(str);
        while(i<l) {
            for(int j=0; j<r; j++) {
                printf("%c", str[i]);
            }
            i++;
        }
        printf("\n");
        
        t--;
    }

    return 0;
}

 

 

 

java 코드

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		
		int t= s.nextInt();
		
		while(t!=0) {
			
			int l=s.nextInt();
			String str = s.next();
			
			
			for(int i=0; i<str.length(); i++) {
				for(int j=0; j<l; j++) {
					System.out.print(str.charAt(i));
				}
			}
			
			System.out.println();
			t--;
		}
		
		
	}
}

 

 

 

 

 

 

2. 1002번 터렛 [ java ] 

실버 3

https://www.acmicpc.net/problem/1002

 

1002번: 터렛

각 테스트 케이스마다 류재명이 있을 수 있는 위치의 수를 출력한다. 만약 류재명이 있을 수 있는 위치의 개수가 무한대일 경우에는 -1을 출력한다.

www.acmicpc.net

기하학 문제로 원의 내접, 외접 등 위치 관계를 활용해 풀어보았다.

반지름과 거리 사이의 관계가 어떠면 접하고, 만나지 않는지 등등의 수학적 개념을 활용했다.

 

 

자바에서 절댓값을 구하는 메소드

Math.abs()

 

 

정답 코드

import java.util.Scanner;

public class Ec2 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		
		int t = s.nextInt();
		int [] result = new int[t];
		int x1=0;
		int y1=0;
		int r1=0;
		int x2=0;
		int y2=0;
		int r2=0;
		int n=0;
		
		while(n!=t) {
			
			result[n]=0;
			
			x1=s.nextInt();
			y1=s.nextInt();
			r1=s.nextInt();
			x2=s.nextInt();
			y2=s.nextInt();
			r2=s.nextInt();
			
			double d= Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
			
			
			//원의 위치 관계 보고 활용..ㅎㅅㅎ
			if(x1==x2 && y1==y2 && r1==r2) { //동일
				result[n]=-1;
			} else if(r1-r2==d || r2-r1==d) { //내접
				result[n]=1;
			} else if(d==(r1+r2)) { //외접
				result[n]=1;
			} else if(d>(r1+r2)) { //외부에 있다
				result[n]=0;
			} else if(d<Math.abs(r1-r2)) { //내부에 있다
				result[n]=0;
			} else { //두 점에서 만난다
				result[n]=2;
			}
			
			n++;
		}
		
		for(int i=0; i<t; i++) {
			System.out.println(result[i]);
		}
	}
}

 

 

 

728x90
Comments