0과 1로 이루어진 어떤 문자열 x에 대한 이진 변환을 다음과 같이 정의한다.
1. x의 모든 0을 제거한다.
2. x의 길이를 c라고 하면, x를 "c를 2진법으로 표현한 문자열"로 바꾼다.
예를 들어, x = "0111010"
이라면, x에 이진 변환을 가하면 x = "0111010" -> "1111" -> "100"
이 된다.
0과 1로 이루어진 문자열 s가 매개변수로 주어진다. s가 "1"이 될 때까지 계속해서 s에 이진 변환을 가했을 때, 이진 변환의 횟수와 변환 과정에서 제거된 모든 0의 개수를 각각 배열에 담아 return 하도록 solution 함수를 완성하라.
public class Solution {
public int[] solution(String string) {
int[] answer = {};
int countZero = 0;
String binary = "";
int count = 0;
while (!string.equals("1")) {
String text = string.replace("0", "");
countZero += string.length() - text.length();
int textLength = text.length();
binary = Integer.toBinaryString(textLength);
string = binary;
count += 1;
}
answer = new int[]{count, countZero};
return answer;
}
}
💡 replace( ) 메서드
어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환한다.
String text = string.replace("0", "");
countZero += string.length() - text.length();