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

The Flawless Bead·2023년 3월 13일
0

프로그래머스

목록 보기
19/20

🔗문제 보러가기 👉 이진 변환 반복하기



📌 문제의 핵심

  1. Integer.toBinaryString(int) : 10진수를 2진수로 변환하여 String으로 반환
  2. 재귀함수

✅ 문제 풀이

  1. 재귀함수 toBinary(String 2진수, int[] answer) 를 선언
    • 2진수 문자열에서 "0"을 ""로 치환
    • 이진 변환의 횟수 : answer[0]++
    • 제거된 모든 0의 개수 : 0을 지우기 전의 문자열 길이(before) - 지운 후의 문자열 길이(after)
    • after의 길이(int)를 2진수(String)로 변환해서 toBinary() 호출
    • before가 1일때 return 하면서 재귀함수 멈춤
class Solution {
    
    public int[] solution(String s) {
        int[] answer = new int[2];
        toBinary(s, answer);
        return answer;
    }
    
    public static void toBinary(String before, int[] answer) {
        if(before.equals("1")) return;
        
        String after = before.replace("0", "");
        answer[0]++;
        answer[1] += before.length() - after.length();
        
        toBinary(Integer.toBinaryString(after.length()), answer);
    }
}

profile
오늘을 살고 내일을 꿈꾸는 낭만주의자

0개의 댓글