본문 바로가기
2022 하반기/algorithm

백준 2226 java

by concho 2023. 1. 8.

 

핵심 키워드 : BigInteger 사용, 특정한 수열에 맞는 조건을 찾아 이를 수학적인 식으로 변환

수학적인 식을 사용해 재귀나 반복을 통해 해답을 도출한 문제

https://juliabiolat.tistory.com/37

 

[백준] Baekjoon 2226번 이진수

▶ 시도 1 => 실패 - 걍 무식하게 한번 해봄, 역시나 시간 초과나옴 개킹받음, 무식의 결과는 시간초과인가 - 생각하기 싫은데 그냥 머리를 돌려야할듯 - 이미 저거 100이 넘어가면 돌렸을 때 뭐 나

juliabiolat.tistory.com

자세한 풀이는 위 블로그를 참조 (블로그 주인이 내 알고리즘을 배껴감)

package BjPack;

import java.util.Scanner;
import java.math.BigInteger;

public class _2226 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		long N = 0, k = 0, cnt = 0;
		N = input.nextInt();

		if (N == 1)
			System.out.printf("0");
		else if (N == 2)
			System.out.printf("1");
		else if (N == 3)
			System.out.printf("1");
		else if (N == 4)
			System.out.printf("3");
		else if (N == 5)
			System.out.printf("5");
		else {
			k = N - 6;
			BigInteger BigM = BigInteger.valueOf(1);
			while (cnt < k) {
				if (cnt % 2 == 0) {
					// M = 2 * M + 1;
					BigM = BigM.multiply(BigInteger.valueOf(2));
					BigM = BigM.add(BigInteger.valueOf(1));
				} else if (cnt % 2 == 1) {
					// M = 2 * M - 1;
					BigM = BigM.multiply(BigInteger.valueOf(2));
					BigM = BigM.subtract(BigInteger.valueOf(1));
				}
				cnt++;
			}

			BigInteger BigS = new BigInteger("2");
			// 2^(N-4)
			for (int i = 1; i < N - 4; i++) {
				BigS = BigS.multiply(BigInteger.valueOf(2));
			}
			// sol = 3*S + k;
			BigS = BigS.multiply(BigInteger.valueOf(3));
			BigS = BigS.subtract(BigM);

			System.out.println(BigS);
		}

	}

}

'2022 하반기 > algorithm' 카테고리의 다른 글

백준 15828 java  (0) 2023.01.08
백준 2164 java  (0) 2023.01.08
백준 18528 java  (0) 2023.01.08

댓글