프로그래머스 - 이진 변환 반복하기 (Level 2)

2023. 12. 31. 21:10코딩테스트 정리(자바)

728x90

처음 풀이

-> 시간 초과

class Solution {
    public int[] solution(String s) {
        int cnt=0; //0의 개수를 기록할 변수
        int len=0; //s의 길이를 기록할 변수
        int count=0; //이진변환 횟수 기록할 변수
        StringBuilder sb=new StringBuilder();
        while(s!="1"){
            for(char ch:s.toCharArray()){
                if(ch=='0'){
                    cnt++;
                }
                else
                    sb.append(ch); 
            }
            s=sb.toString(); //문자열로 변환
            len=s.length(); //길이 반환
            s=Integer.toString(len,2); //길이를 2진법으로 표현한 문자열로 변환
            count++;
        }
        int[] answer = {count,cnt};
        return answer;
    }
}

 

두 번째 풀이

-> 시간 초과

class Solution {
    public int[] solution(String s) {
        int cnt=0; //0의 개수를 기록할 변수
        int len1=0; //s의 길이를 기록할 변수
        int len2=0; //0 제거 후 s의 길이를 기록할 변수
        int count=0; //이진변환 횟수 기록할 변수

        while(s!="1"){
            len1=s.length();
            s=s.replaceAll("0",""); //0 제거
            len2=s.length();
            cnt+=len1 - len2; //0의 개수
            s=Integer.toString(len2,2); //길이를 2진법으로 표현한 문자열로 변환
            count++;
        }
        int[] answer = {count,cnt}; 
        return answer;
    }
}

 

-> 이유를 알았다

반복문의 조건을 이렇게 바꿔줘야 돌아간다.

시간초과가 아니라 멈췄던 것.

while(!s.equals("1")){
            len1=s.length();
            s=s.replaceAll("0",""); //0 제거
            len2=s.length();
            cnt+=len1 - len2; //0의 개수
            s=Integer.toString(len2,2); //길이를 2진법으로 표현한 문자열로 변환
            count++;
        }

 

문자열의 동등성을 비교할 때 == 연산자를 사용하면 안 되는 이유는 == 연산자가 객체의 참조를 비교하기 때문입니다.

즉, == 연산자는 두 문자열이 같은 객체를 가리키고 있는지를 확인합니다.

반면에 equals() 메서드는 두 문자열의 내용이 같은지를 확인합니다.

따라서 문자열의 내용을 비교하려면 equals() 메서드를 사용해야 합니다.

-> 이런 이유로 equals 메서드를 사용해야 한다.

 

 

 

1.

 int[] answer = {count, cnt}; //변수로도 원소 지정 가능

int[] anser=new int[] {loop,removed}; //이렇게 초기화하면서 생성도 가능

 

 

2.  s = s.replaceAll('0', "");

: 문자열의 모든 0을 없애는 방법

replace(char oldchar, char newchar)

-> 문자열의 oldchar 문자를 newchar 문자로 치환한 문자열을 반환

 

 

 

좋은 풀이

-> 0의 개수를 세고 전체 문자열 길이에서 빼주면 0을 제거했을 때의 문자열 길이를 알 수 있다.

0을 제거할 필요가 없었다. 0의 개수만 세면 되었음.

public class Solution {
    private int countZeros(String s) {
        int zeros = 0;
        for (char c : s.toCharArray()) {
            if (c == '0') zeros++;
        }
        return zeros;
    }

    public int[] solution(String s) {
        int loop = 0;
        int removed = 0;

        while (!s.equals("1")) {
            int zeros = countZeros(s);
            loop += 1;
            removed += zeros;

            int ones = s.length() - zeros;
            s = Integer.toString(ones, 2);
        }

        return new int[] {loop, removed};
    }
}
728x90