https://school.programmers.co.kr/learn/courses/30/lessons/70129
문제 풀이는 매우 간단하다.
문자열이 1이 될 때까지, 1의 개수를 구한 후
하지만, 아래 코드로 제출하니 시간초과가 발생했다.
class Solution {
public int[] solution(String s) {
int[] answer = new int[2];
int cnt_conv=0;
int cnt_zero=0;
while(s!="1"){
int c=s.replace("0","").length(); // 1의 개수
cnt_zero+=(s.length()-c); // 0의 개수
s = Integer.toBinaryString(c); // c를 2진 문자열로 변환
cnt_conv+=1;
}
answer[0]=cnt_conv;
answer[1]=cnt_zero;
return answer;
}
}
Integer.toBinaryString(1)은 "01"을 반환한다.
입출력 결과를 잘 살펴보면 c=1일 경우 이진 변환 결과 1로 보고 종료한다.
따라서, while 루프에서 c==1일 경우 루프를 빠져나오도록 수정하면 된다!
while(s!="1"){
int c=s.replace("0","").length(); // 1의 개수
cnt_zero+=(s.length()-c); // 0의 개수
s = Integer.toBinaryString(c); // c를 2진 문자열로 변환
cnt_conv+=1;
if(c==1) break; // Integer.toBinaryString(1)은 "01"을 반환함
}
GitHub Java-algorithm-practice/프로그래머스/lv2/70129. 이진 변환 반복하기/
class Solution {
public int[] solution(String s) {
int[] answer = new int[2];
int cnt_conv=0;
int cnt_zero=0;
while(s!="1"){
int c=s.replace("0","").length(); // 1의 개수
cnt_zero+=(s.length()-c); // 0의 개수
s = Integer.toBinaryString(c); // c를 2진 문자열로 변환
cnt_conv+=1;
if(c==1) break; // Integer.toBinaryString(1)은 "01"을 반환함
}
answer[0]=cnt_conv;
answer[1]=cnt_zero;
return answer;
}
}