[프로그래머스] 이진 변환 반복하기 (Lv2)

meong·2023년 3월 21일
0

코테 공부

목록 보기
5/10
post-thumbnail

문제

https://school.programmers.co.kr/learn/courses/30/lessons/70129


고민1. 실행 시간 초과

문제 풀이는 매우 간단하다.
문자열이 1이 될 때까지, 1의 개수를 구한 후

  • 0의 개수는 누적 저장하고
  • 1의 개수는 2진 문자열로 변환하여 저장하면 된다
    -> (Integer.toBinaryString() 함수 사용)

하지만, 아래 코드로 제출하니 시간초과가 발생했다.

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;
    }
}
profile
새싹 개발자

0개의 댓글