이진변환 반복하기

Jobmania·2022년 11월 14일
0

위와 같이 '제거한 0의 수'와 1의 갯수를 이진변환하여 나온 결과가 "1"이 될때까지 '반복한 횟수' 두값이 필요하다...

String이 불변한 객체이므로(메모리소모) StringBuffer를 배운 만큼 문자열을 자주 편집하기 때문에 StringBuffer를 통해 풀어보았다. ```

  public int[] solution(String s) {
        int countZero = 0;
        int countConversion= 0;

        StringBuffer str = new StringBuffer(s);
        while(!str.toString().equals("1")){
            int tempZero = 0;
            for(int i = 0 ; i <str.length() ; i ++ ){
                if( str.charAt(i) == '0'){
                    countZero++;
                    tempZero++;
                }
                if(i == str.length()-1){
                    countConversion++;
                    int tempS = str.length()-tempZero; // 6
                    str.delete(0,str.length()); 
                    String binaryString = Integer.toBinaryString(tempS); 
                    str.append(binaryString);
                    break;
                }
            }
        }
        return new int[]{countConversion, countZero};
    }

다른 사람의 풀이를 보니 굳이 Zero 갯수를 정할 필요 없이 길이에서 뺐다. 각 문제에 요소에 대한 연관관계를 깊이 파악해볼 필요가 있다.

profile
HelloWorld에서 RealWorld로

0개의 댓글