[TIL] 241216

MONA·2024년 12월 16일

나혼공

목록 보기
46/92

프로그래머스-이진 변환 반복하기

class Solution {
    public int[] solution(String s) {
        int cnt = 0;
        int zeroCnt = 0;
        while(!s.equals("1")){
            int originLen = s.length();
            s.replaceAll("0", "");
            zeroCnt += originLen - s.length();

            s = Integer.toBinaryString(s.length());
            cnt++;
        }
        return new int[]{cnt, zeroCnt};
    }
}

시간초과

  1. replaceAll은 문자열을 직접 순회하면서 0을 바꾼다.
    • 내부적으로 정규식을 사용하기 때문에 느리다.

어차피 순회할 거 그냥 직접 순회하면서 0의 개수를 카운트하고 동시에 남은 1의 개수를 세도록 한다.

class Solution {
    public int[] solution(String s) {
        int cnt = 0;
        int zeroCnt = 0;
        while(!s.equals("1")){
            int oneCnt = 0;

            for(char c: s.toCharArray()){
                if(c=='0') {
                    zeroCnt++;
                } else {
                    oneCnt++;
                }
            }
            s = Integer.toBinaryString(oneCnt);
            cnt++;
        }
        return new int[]{cnt, zeroCnt};
    }
}
profile
고민고민고민

0개의 댓글