티스토리 뷰

프로그래머스 70129번 - 이진 변환 반복하기

프로그래머스 70129번 - https://programmers.co.kr/learn/courses/30/lessons/70129

 

요구사항

1. 0과 1로 이루어진 문자열이 "1"이 될 때까지 계속해서 이진 변환을 가했을 때, 이진 변환의 횟수와 변환 과정에서 제거된 모든 0의 개수를 각각 배열에 담아 반환하라.

2. 0과 1로 이루어진 어떤 문자열 x에 대한 이진 변환은 다음과 같이 정의합니다.

 

1단계 : x의 모든 0을 제거합니다.

2단계 : x의 길이를 c라고 하면, x를 "c를 2진법으로 표현한 문자열"로 바꿉니다.

 

요구사항 분석 및  풀이과정

1. 이진 변환에서 중요한 점은 1단계도 중요하지만, 결과적으로 1단계를 거친 결과의 길이가 중요합니다. 그 길이는 다음과 같습니다.

 

1단계를 거친 결과의 길이 = c = 문자열 x의 길이 - 0의 개수

 

2. 1단계를 거친 결과의 길이 c를 2진법으로 표현한 문자열과, c를 계산하면서 구한 0의 개수를 Translation 이라는 객체로 묶어 이진 변환 1회를 캡슐화합니다.

 

3. 종료 조건인 이진 변환의 결과가 "1"이 될 때까지 Translation을 수행하고, 수행 횟수와 각 Translation에서 제거한 0의 개수를 누적하면 된다.

 

소스코드 작성

class Solution {

	private static class Translation {

		private final int numOfEraseZero;
		private final char[] result;

		public Translation(int numOfEraseZero, char[] result) {
			this.numOfEraseZero = numOfEraseZero;
			this.result = result;
		}

		public static Translation make(char[] chars) {
			int numOfZero = 0;

			for (char v : chars) {
				numOfZero += (v == '0' ? 1 : 0);
			}

			return new Translation(numOfZero, toBinaryString(chars.length - numOfZero));
		}

		public int getNumOfEraseZero() {
			return numOfEraseZero;
		}

		public char[] getResult() {
			return result;
		}

		public boolean isFinish() {
			return (result.length == 1) && (result[0] == '1');
		}
	}

	private static char[] toBinaryString(int number) {
		final char[] symbols = {'0', '1'};

		int len = (int)(Math.log10(number) / Math.log10(2)) + 1;
		char[] result = new char[len];

		for (int i = 0; i < len; i++) {
			result[len - i - 1] = symbols[number % 2];
			number /= 2;
		}

		return result;
	}

	public int[] solution(String s) {
		int result = 0;
		int count = 0;

		Translation t = Translation.make(s.toCharArray());
		result += t.getNumOfEraseZero();
		count++;

		while (!t.isFinish()) {
			t = Translation.make(t.getResult());
			result += t.getNumOfEraseZero();
			count++;
		}

		return new int[] {count, result};
	}
}

 

결과

 

소스코드 깃허브 주소

링크

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함