알고리즘 문제 풀이
Codility - BinaryGap [Kotlin]
블린더르
2021. 2. 23. 00:11
/*
* 2021-02-22
* https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
*/
fun solution(N: Int): Int {
val binaryString = N.toString(2)
// var num = N
// do {
// binaryString += num % 2
// num /= 2
// } while (num != 1)
// binaryString += "1"
// binaryString = binaryString.reversed()
val zeroList = binaryString.split("1").toMutableList()
if (binaryString.last() != '1') {
// kotlin 1.3
zeroList.removeAt(zeroList.count() - 1)
}
// kotlin 1.3
return zeroList.map { it.count() }.max() ?: 0
}
처음에는 루프를 돌면서 이진수 문자열을 생성했는 데 다 통과했지만 최대 Int 값인 2147483647 가 조건으로 주어졌을 때
시간을 초과하는 문제가 있었다.
toString()
을 이용하여 진법을 변환하도록 수정하여 통과했다.
반응형