코테 연습 with Kotlin - 2

아이모·2022년 9월 23일
0

코테

목록 보기
2/15

<프로그래머스 문제 >

0과 1로 이루어진 어떤 문자열 x에 대한 이진 변환을 다음과 같이 정의합니다.

x의 모든 0을 제거합니다.
x의 길이를 c라고 하면, x를 "c를 2진법으로 표현한 문자열"로 바꿉니다.
예를 들어, x = "0111010"이라면, x에 이진 변환을 가하면 x = "0111010" -> "1111" -> "100" 이 됩니다.

0과 1로 이루어진 문자열 s가 매개변수로 주어집니다. s가 "1"이 될 때까지 계속해서 s에 이진 변환을 가했을 때, 이진 변환의 횟수와 변환 과정에서 제거된 모든 0의 개수를 각각 배열에 담아 return 하도록 solution 함수를 완성해주세요.

<풀이과정>
문제를 보고 생각난 것은 이진수의 경우 0과 1만으로 이루어진 문자열로 표현되기 때문에 정규표현식을 이용하여 0을 제거하면 되겠다는 생각을 하였고 정규표현식을 이용하여 문제를 해결하였다.

<코드>

class Solution {
    fun solution(s: String): IntArray {
        var presentBinary = s
        var presentLength = s.length
        var deleteZero = 0
        var nextBinary = ""
        var previousBinary = s
        var count = 0;
        while(presentBinary.length > 1){
            count ++;
            if(presentBinary.contains("0")) {
                previousBinary = presentBinary
                presentBinary = presentBinary.replace("[^1]".toRegex(), "")
                deleteZero += previousBinary.length - presentBinary.length
                nextBinary = Integer.toBinaryString(presentBinary.length)
            }
            else{
               nextBinary =  Integer.toBinaryString(presentBinary.length)
            }
            presentBinary = nextBinary
        }
        var answer: IntArray = intArrayOf(count, deleteZero)
       
        return answer
    }
    

}
profile
데이터로 보는 실력

0개의 댓글