240104 표현 가능한 이진트리

Jongleee·2024년 1월 4일
0

TIL

목록 보기
460/737
private int[] answer;

public int[] solution(long[] numbers) {
	answer = new int[numbers.length];
	for (int i = 0; i < numbers.length; i++) {
		answer[i] = 1;
		long number = numbers[i];
		int numberLength = (int) Math.floor(Math.log(number) / Math.log(2)) + 1;
		int exp = 1;
		int treeLength = 0;
		while (treeLength < numberLength) {
			treeLength = (int) Math.pow(2, exp++) - 1;
		}

		boolean[] node = new boolean[treeLength];
		int index = treeLength - 1;

		while (number > 0) {
			long div = number / 2;
			long mod = number % 2;
			number = div;
			node[index--] = (mod == 1);

			if (div == 0)
				break;
		}

		solve(node, 0, treeLength - 1, false, i);
	}
	return answer;
}

private void solve(boolean[] node, int s, int e, boolean isEnd, int i) {
	int mid = (s + e) / 2;
	boolean currentNode = node[mid];

	if (isEnd && currentNode) {
		answer[i] = 0;
		return;
	}

	if (s != e) {
		solve(node, s, mid - 1, !currentNode, i);
		solve(node, mid + 1, e, !currentNode, i);
	}
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/150367

0개의 댓글