License key formatter

Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fun licenseKeyFormatting(S: String, K: Int): String {
val stringBuilder: StringBuilder = StringBuilder()
var count = 0
for (i in S.length - 1 downTo 0) {
if (S[i] != '-') {
if (count == K) {
stringBuilder.append("-")
count = 0
}
stringBuilder.append(S[i].toUpperCase())
count++
}
}

return stringBuilder.reverse().toString()
}