[Java] SWEA.18662 등차수열

정석·2024년 5월 17일

알고리즘 학습

목록 보기
41/67
post-thumbnail

세 정수가 주어졌을 때 등차수열이 되도록 만들 수 있는 최소 값 X 를 구하기

▶︎ 💡 문제 링크

💡알고리즘

  1. 등차수열의 조건을 통해 a를 변경해서 X 를 구할지, b를 변경해서 구할지, c 를 변경해서 구할지에 따라 세가지의 경우가 나오므로 각 경우를 구해서 최솟값을 찾는다.
  2. 변화량을 구하는 것이므로 절댓값 Math.abs() 를 활용한다.
  3. 변화량은 각 숫자별 차이이므로 절댓값에서 2를 나눠준다.
  4. 문제에서 소숫점 첫째자리까지 표현하라 했기에 %.1f 를 활용하며, 결과 값은 double 로 저장한다.
  5. 세 개의 결과에 대한 최솟값을 구할 때 Math.min() 을 활용한다.

코드

public class swea_등차수열 {

	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int T = Integer.parseInt(br.readLine());
		
		while(T-- > 0) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			double a = Integer.parseInt(st.nextToken());
			double b = Integer.parseInt(st.nextToken());
			double c = Integer.parseInt(st.nextToken());
			
			double x1 = Math.abs(2.0*b - c - a)/2.0;
			double x2 = Math.abs(a + c - 2.0 * b)/2.0;
			double x3 = Math.abs(2.0*b - a - c)/2.0;
			
			
			double result = Math.min(x1, Math.min(x2, x3));
			
			System.out.printf("#%d %.1f%n", T, result);	
		}
	}
}

기억할 점

  • Math.min(a, Math.min(b,c)) 로 세가지 이상의 수도 최솟값 비교 가능

  • Math.abs(a-b) 절댓값 구하기

  • System.out.printf() 로 출력할 때 포맷팅 종류

public class Main {
    public static void main(String[] args) {
        int intValue = 42;
        double doubleValue = 3.141592;
        String stringValue = "Hello";
        boolean boolValue = true;
        char charValue = 'A';

        System.out.printf("정수: %d%n", intValue);
        System.out.printf("실수: %f%n", doubleValue);
        System.out.printf("실수 (소수점 이하 2자리): %.2f%n", doubleValue);
        System.out.printf("지수 표기: %e%n", doubleValue);
        System.out.printf("문자열: %s%n", stringValue);
        System.out.printf("불리언: %b%n", boolValue);
        System.out.printf("문자: %c%n", charValue);

        System.out.printf("정렬 (왼쪽 정렬, 10자리): %-10s%n", stringValue);
        System.out.printf("정렬 (오른쪽 정렬, 10자리): %10s%n", stringValue);
        System.out.printf("부호: %+d%n", intValue);
        System.out.printf("채우기 문자: %010d%n", intValue);
        System.out.printf("천 단위 구분자: %,d%n", 1000000);
    }
}

0개의 댓글