[Kotlin] Korean Coding Test - Programmers - Repeat binary transformation

Kotlin

2023-10-25 18:38 (KST)

Language :

Question

Link

We define a binary transformation for a string x of 0s and 1s as follows.

  • Remove all zeros of x.
  • If we let the length of x be c, we replace x with "a binary string of c".

For example, if x = "0111010", applying a binary transformation to x = "0111010" -> "1111" -> "100".

A string of 0s and 1s is given as a parameter. When binary transformation is applied to s continuously until s becomes "1", complete the solution function so that the number of binary transformation and the number of zeros removed during the transformation are returned to the array, respectively.

Restrictions

The length of s is 1 or more and 150,000 or less.

s contains at least one '1'.

Input/Output Example

Input/Output Example #1

  • Input: "110010101001"
  • Output: [3,8]

Input/Output Example #2

  • Input: "01110"
  • Output: [3,3]

Input/Output Example #3

  • Input: "1111111"
  • Output: [4,1]

Code 1

class Solution {
    fun solution(s: String): IntArray {
        var target = s
        var removeCount = 0
        var convertCount = 0
        while(target != "1") {
            convertCount++
            removeCount += target.count { it == '0' }
            target = Integer.toBinaryString(target.replace("0", "").length)
        }
        return intArrayOf(convertCount, removeCount)
    }
}
TEST 1 〉	Pass (11.32ms, 60.6MB)
TEST 2 〉	Pass (32.29ms, 62.8MB)
TEST 3 〉	Pass (8.24ms, 61.2MB)
TEST 4 〉	Pass (8.14ms, 60.2MB)
TEST 5 〉	Pass (8.04ms, 61.4MB)
TEST 6 〉	Pass (10.04ms, 60.9MB)
TEST 7 〉	Pass (8.84ms, 63.2MB)
TEST 8 〉	Pass (10.01ms, 63MB)
TEST 9 〉	Pass (16.71ms, 62MB)
TEST 10 〉	Pass (25.73ms, 61.5MB)
TEST 11 〉	Pass (27.83ms, 61.9MB)

Code 2. Speed improvement (without replace function)

class Solution {
    fun solution(s: String): IntArray {
        var target = s
        var removeCount = 0
        var convertCount = 0
        while(target != "1") {
            convertCount++
            target.count { it == '0' }.apply {
                removeCount += this
                target = Integer.toBinaryString(target.length - this)
            }
        }
        return intArrayOf(convertCount, removeCount)
    }
}
TEST 1 〉	Pass (0.04ms, 62MB)
TEST 2 〉	Pass (7.91ms, 60.8MB)
TEST 3 〉	Pass (0.05ms, 61.8MB)
TEST 4 〉	Pass (0.05ms, 62.7MB)
TEST 5 〉	Pass (0.03ms, 61.8MB)
TEST 6 〉	Pass (0.08ms, 61.1MB)
TEST 7 〉	Pass (0.13ms, 62.2MB)
TEST 8 〉	Pass (0.13ms, 59.8MB)
TEST 9 〉	Pass (4.89ms, 59.4MB)
TEST 10 〉	Pass (9.02ms, 60.1MB)
TEST 11 〉	Pass (5.83ms, 60.5MB)

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.