728x90

[문제 링크]

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 


 

class Solution {
    public int[] solution(String s) {
        int cnt = 0; //변환 수
        int num = 0; //0의 수
        
        int temp1 = 0; //이전 길이
        int temp2 = 0; //0 지운 길이
        
        while(s.length() > 1)
        {
            temp1 = s.length();
            s = s.replace("0", "");
            temp2 = s.length();
            
            num += temp1 - temp2;
            
            s = Integer.toBinaryString(temp2);
            cnt++; 
        }
        
        return new int[] {cnt, num};
    }
}

 

접근법

  1. 0을 제거한다.
  2. 제거 하기 전과 후의 길이를 비교하여 삭제된 0의 개수를 계산한다.
  3. Integer.toBinaryString() 함수를 사용하여 0이 제거된 수를 이진 변환한다.
  4. 이진 변화된 수를 계산한다.
  5. 배열로 반환한다.

이진 변화 함수를 사용하지 않는 방법은 코드가 길어지기에 함수를 사용하여 간단하게 작성했다.

 

728x90

+ Recent posts