2023-04-22 이진 변환 반복하기

문제 정의

0과 1로 이루어진 문자열 s 가 “1” 이 될 떄까지 두 번에 걸쳐 변환하는 작업을 반복해야 한다.

첫번째 변환. s 에서 0을 제외하고 1 만 남긴다. 두번째 변환. 변환된 s 의 길이를 c 라고 할 때, c 를 2진수로 나타낸 문자열로 변환한다.

해결한 방법

  1. 첫번째 과정은 java 8 stream 을 이용하였다.

    1
    2
    
     String firstConverted = s.chars().filter(ch -> ch == '1')
     .mapToObj(ch -> Character.toString(ch)).collect(Collectors.joining());
    

filter() 메소드를 이용하여 “1” 인 문자들만 걸러준 뒤, mapToObj 에서 int stream 의 원소들을 String 타입으로 변환. 이후에, Collectors 모듈의 joining() 메소드로 이 문자들을 하나의 String 타입으로 모아서 반환.

  1. 두번째 과정은 Integer.toString(myIntgerValue, 2);

Integer 클래스의 buil-in 메소드를 이용해 2진법의 문자열로 변환.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.stream.Collectors;

class Solution {
	public int[] solution(String s) {
		int[] ans = {0, 0};
		while (!s.equals("1")) {
			String firstConverted = s.chars().filter(ch -> ch == '1')
				.mapToObj(ch -> Character.toString(ch)).collect(Collectors.joining());

			ans[1] += (s.length() - firstConverted.length());
			ans[0] += 1;
			s = Integer.toString(firstConverted.length(), 2);
		}

		return ans;
	}
}

Collectors 모듈의 다양한 collector 활용 예제

Baeldung Collectors 예제

comments powered by Disqus