class Solution {
fun validUtf8(data: IntArray): Boolean {
val size = data.size
var i = 0
while (i < size) {
val byte = getByte(data[i])
if (byte == -1) return false
for (j in 1 until byte) {
if (i + j >= size) return false
// 11000000 => 10000000
if (data[i + j].and(192) != 128) return false
}
i += byte
}
return true
}
fun getByte(value: Int): Int {
return when {
value.and(128) == 0 -> 1 // 10000000 => 00000000
value.and(224) == 192 -> 2 // 11100000 => 11000000
value.and(240) == 224 -> 3 // 11110000 => 11100000
value.and(248) == 240 -> 4 // 11111000 => 11110000
else -> -1
}
}
}