Kotlin Leetcode - 338. Counting Bits
class Solution {
fun countBits(n: Int): IntArray {
}
}
解題思路
這一題考的是二進位操作的熟悉度
有個小觀察是
我們可以利用之前已經計算過的答案
來避免為每個數字重新計算位元
比方說,我們已經知道了 10 (1010) 來說,1 的位元數是 2
那麼我們可以知道,數字剛好為兩倍的答案也會是 2(20,10100)
數字是兩倍加一的答案,則會多一(21,10101)
Kotlin 參考解答
class Solution {
fun countBits(num: Int): IntArray {
val ans = IntArray(num + 1)
for (index in 0..num) {
ans[index] = index % 2 + ans[index / 2]
}
return ans
}
}
回到 leetcode 列表