본문 바로가기
코딩테스트 준비/프로그래머스

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

by 코딩하는 돼징 2023. 9. 12.
반응형

 

 

많이 풀어본 이진법 문제가 나와서 나름 금방 풀었던 것 같다.

반복문 2개를 써도 되나 고민하면서 풀었는데 통과되어서 다행이다!

 

using System;
using System.Linq;
using System.Collections.Generic;
public class Solution {
    public int[] solution(string s) {
        int[] answer = new int[2];
        int count_0 = 0;
        int count = 0;

        while(s!= "1")
        {
            count++;
            List<char> s_string = new List<char>(s);
            count_0 += s_string.Count(n => n=='0');

            string a = s.Replace("0","");
            int a_len = a.Length;

            string answer_string ="";

            while(a_len>0)
            {
                if (a_len % 2 == 0)
                {
                    answer_string += "0";
                }
                if (a_len % 2 == 1)
                {
                    answer_string += "1";
                }

                a_len /= 2;
            }
            s = answer_string;
        }
        answer[0] = count;
        answer[1] = count_0;
        return answer;
    }
}

 

 

 

 

반응형

댓글