2. 누적된 제거 횟수와 0의 개수를 배열로 반환

    앞서 작성한 solution() 메서드에서 배열을 반환합니다.

    이렇게 자바의 진법 변환 메서드를 사용해서 문제를 풀 수 있습니다.

     

    전체 코드

    4장/이진_변환_반복하기.java

    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};
        }
    }
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.