問題: We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1.
方法: 遍歷陣列,如果當前bit為0則指標移動一位,因為0必為first character;如果當前bit為1則指標移動兩位,因為1X必為second character。當遍歷到陣列尾端時,如果指標正好等於陣列最後一個元素的下標,則返回true;否則,陣列尾端必為10,返回false。
具體實現:
class IsOneBitCharacter {
fun isOneBitCharacter(bits: IntArray): Boolean {
var i = 0
while (i <= bits.lastIndex - 1) {
if (bits[i] == 0) {
i++
} else if (bits[i] == 1) {
i += 2
}
}
if (i == bits.lastIndex) {
return true
}
return false
}
}
fun main(args: Array<String>) {
val array = intArrayOf(0, 0, 0, 0)
val isOneBitCharacter = IsOneBitCharacter()
val result = isOneBitCharacter.isOneBitCharacter(array)
println("result: $result")
}
複製程式碼
有問題隨時溝通